【问题标题】:How to fix image download python如何修复图像下载python
【发布时间】:2019-06-13 15:29:05
【问题描述】:

我无法保存从汤对象获取的图像,如果我将其复制并粘贴到浏览器中,图像源是正确的,但我似乎无法下载它

我使用BeautifulSoup 查找图像然后requests 下载它,我也尝试使用urllib.urlretrieve 下载它但没有成功最后我使用lxml.html 解析并获取图像并下载它使用二进制解码

import bs4,urllib2,requests
REGISTER_URL="http://example.webscraping.com/places/default/user/register?_next=/places/default/index%22"
html=urllib2.urlopen(REGISTER_URL)
soup=bs4.BeautifulSoup(html,"html.parser")
image=soup.find("img",src=True)
print image['src']
#print image['src']
response=requests.get(image['src'])
'''
f=open("Cas.jpg")
for block in response.iter_content(1024):
    f.write(block)
f.close()
'''

我想知道为什么requestsurllib.urlretrieve 下载它不起作用,注意:urllib.urlretrieve 下载黑色图像,而请求只会给出错误。 我的预期结果只是下载验证码图像

注意1:图片是来自Python web-scraping example的验证码,当然每次加载页面都会收到一张新图片。

注意2:这绝不是对网站的攻击或任何有害行为,本网站仅作为测试爬虫的示例。

【问题讨论】:

  • 对于那些给予 -rep 的人,请在 cmets 中解释原因,以便我可以在未来处理我的“问题”

标签: python python-2.7 web-scraping beautifulsoup


【解决方案1】:

图片在网站上显示为Base64。您可以从 src 获取数据字符串,对其进行解码,然后保存为图像。

from bs4 import BeautifulSoup
import requests
import base64
url = "http://example.webscraping.com/places/default/user/register?_next=/places/default/index%22"
r=requests.get(url)
soup=BeautifulSoup(r.text,'html.parser')
imgstring=soup.find('img')['src'].split(',')[1]
filename = 'image.jpg'
imgdata = base64.b64decode(imgstring)
with open(filename, 'wb') as f:
    f.write(imgdata)

图片.jpg

【讨论】:

  • 效果很好,请问你怎么知道是base64,还有imgdata = base64.b64decode(imgstring)可以详细说明
  • @AmjasdMasdhash 是的。二进制图像数据被编码为 ASCII 并在图像源中使用。我们必须将其解码回来以获取二进制数据。只有这样我们才能将其转换回文件。
  • @AmjasdMasdhash 图片来源不是网址。您可以使用检查工具找出答案。
  • 但是如果你复制粘贴 src 到 Firefox 中它会打开图片
  • @AmjasdMasdhash 浏览器进行解码。请求没有。
猜你喜欢
  • 1970-01-01
  • 2013-01-27
  • 2022-09-28
  • 1970-01-01
  • 1970-01-01
  • 2014-02-19
  • 2021-10-23
  • 2020-04-09
  • 2020-07-20
相关资源
最近更新 更多