使用Beautifulsoup在没有HTML的情况下下载图像' img'标签

时间:2017-11-28 21:34:41

标签: python python-3.x web-scraping beautifulsoup

我使用beautifulsoup查找和下载来自指定网站的图片,但该网站包含的图片不是通常的<img src="icon.gif"/>格式:

例如,导致我出现问题的是这样的:

<form action="example.jpg">

<!-- <img src="big.jpg" /> -->

background-image:url("xine.png");

我找到图片的代码是:

webpage = "https://example.com/images/"
soup = BeautifulSoup(urlopen(webpage), "html.parser")

for img in soup.find_all('img'):
    img_url = urljoin(webpage, img['src'])
    file_name = img['src'].split('/')[-1]
    file_path = os.path.join("C:\\users\\images", file_name)
    urlretrieve(img_url, file_path)

我想我可能不得不使用正则表达式,但希望我不必这样做。

提前致谢

1 个答案:

答案 0 :(得分:1)

修改传递给urlretrieve的路径,以准确指定要将文件复制到的位置:

file_path = os.path.join('c:\files\cw\downloads', file_name)
urlretrieve(img_url, file_path)

编辑: 看起来您还试图在评论中找到img标签。建立Find specific comments in HTML code using python

...
imgs = soup.find_all('img')
comments = soup.findAll(text=lambda text:isinstance(text, bs4.Comment))
for comment in comments:
    comment_soup = bs4.BeautifulSoup(comment)
    imgs.extend(comment_soup.findAll('img'))

for img in imgs:
    ...
相关问题