如何修复图片下载python

2024-03-29 11:16:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我用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:这绝不是对网站的攻击或任何有害行为,本网站仅作为测试刮刀的示例。你知道吗


Tags: 图像imagesrcregisterurlexamplehtmlurllib2
1条回答
网友
1楼 · 发布于 2024-03-29 11:16:40

图像在站点上以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你知道吗

enter image description here

相关问题 更多 >