我使用 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)
我想我可能必须使用正则表达式,但希望我不必这样做。
提前致谢
最佳答案
修改传递给 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:
...
关于python - 使用不带 HTML 'img' 标签的 Beautifulsoup 下载图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47541274/