【问题标题】:Get image url with BeautifulSoup where src= data:image/gif;base64,使用 BeautifulSoup 获取图像 url,其中 src= data:image/gif;base64,
【发布时间】:2021-01-26 13:02:04
【问题描述】:

我正在尝试使用 Python 和 BeautifulSoup4 获取网页中图像的网址

我当前的代码是


import requests

from bs4 import BeautifulSoup

url="https://goibibo.com/hotels/hotels-in-shimla-ct/"

#Headers

headers={
    'User-Agent':"Mozilla/5.0 (x11; Linux x86_64) AppleWebkit/537.36 (KHTML, like Gecko Chrome 77.0.3865.90 Safari/537.36)"
}

data = requests.get(url,headers=headers).text
soup = BeautifulSoup(data, 'html.parser')

images = soup.find_all('img',src=True)

print('Number of Images: ', len(images))
print('\n')
for image in images:
    if(image.has_attr('src')):
        print(image['src'])

当我检查图像元素时,它有一个正确的 URL (src="https://cdn1.goibibo.com/voy_ing/t_g/812aa1726b8211e7a0a10a4cef95d023.jpg")。但是,当我使用 BeautifulSoup4 获取 img 元素的 src 值时,它会返回 data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAAAAAAEAAAIBRAA7

如何获取网页中给出的图片url?

【问题讨论】:

  • 您能提供您尝试抓取的网站的实际网址吗?
  • @Sushil tryna 是什么?
  • Tryna 的意思是尝试...我懒得把它完全输入 XD。但是,是的,我同意你的观点@baduker。没有实际的url,我们无法解决此类问题。
  • 用实际的 URL 更新我的问题....

标签: python beautifulsoup


【解决方案1】:

此 img 标签不包含对某些图像 url 的引用,它包含 base64 格式的图像本身(例如,参见 w3docs)。

要对其进行解码,您需要在base64, 之后获取字符串:

string = string.split('base64,')[1]

将其解码为字节数组:

import base64
decoded = base64.decodebytes(string.encode("ascii"))

并且该字节数组可以写入文件:

with open('output.gif', 'wb') as f:
    f.write(decoded)

通常它应该稍微复杂一些,因为您需要考虑在数据 URI data:image/gif; 开头提供的图片格式(也可以是 png、jpg、svg),但这也不应该不会很复杂。

【讨论】:

  • 但是我的麻烦是HTML中指示的url无法检索。我尝试在 BeautifulSoup 中使用其他解析器,但没有结果......
猜你喜欢
  • 2014-04-15
  • 1970-01-01
  • 2016-04-27
  • 1970-01-01
  • 2012-05-15
  • 2021-12-05
  • 2021-11-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多