0
有人能告訴我如何使用BeautifulSoup獲取網頁中所有圖像的aboslute路徑列表嗎?使用BeautifulSoup獲取頁面中所有圖像的絕對路徑列表
獲取所有圖像很簡單。我這樣做:
page_images = [image["src"] for image in soup.findAll("img")]
...但我有困難獲得絕對路徑。任何幫助?
謝謝。
有人能告訴我如何使用BeautifulSoup獲取網頁中所有圖像的aboslute路徑列表嗎?使用BeautifulSoup獲取頁面中所有圖像的絕對路徑列表
獲取所有圖像很簡單。我這樣做:
page_images = [image["src"] for image in soup.findAll("img")]
...但我有困難獲得絕對路徑。任何幫助?
謝謝。
您必須在獲取路徑後對路徑進行規範化。這可以使用urlparse.urljoin
完成。例如:
>>> urlparse.urljoin("http://google.com/some/path/", "../../img/icon.png")
'http://google.com/img/icon.png'
這是不使用BeautifulSoup,但更優雅(和維護良好的)LXML + pyquery:
import pyquery
from urlparse import urljoin
def make_images_absolute(self):
self('img').each(lambda: self(this).attr('src',
urljoin(self.base_url, self(this).attr('src'))))
url="http://lwn.net"
pq = pyquery.PyQuery(url)
for i in pq("img"):
print i.attrib["src"]
make_images_absolute(pq)
for i in pq("img"):
print i.attrib["src"]