python - 使用不带 HTML 'img' 标签的 Beautifulsoup 下载图像

标签 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)

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

提前致谢

最佳答案

修改传递给 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/

相关文章:

python - 为什么 PostgreSQL 适配器 psycopg2 在 Google App Engine dev_appserver.py 中失败?

python - 如何对分支 python 版本实现 100% 覆盖?

python - str.translate 方法没有替换

python-3.x - 抓取 Google 翻译 Python

python - 使用来自另一个数据帧的信息重新组合一个数据帧中的数据

python - py.test -- 模拟常量并在测试函数中引发异常

python - 如何从调用模块的脚本中使用模块中的变量

python - 流式传输解压存档

python - 从点击跟踪中抓取数据

python - 通过scrapy在一个页面中下载多张图片