帮忙看个问题
import requestsfrom bs4 import BeautifulSoup
import time
url = "https://www.umei.cc/tupiandaquan/dongwutupian/"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36"
}
resp = requests.get(url,headers = headers)
resp.encoding = "utf-8"
# print(resp.text)
main_page = BeautifulSoup(resp.text,"html.parser")
main_list = main_page.find("div",class_="TypeList").find_all("a") #图片一级页面地址
# print(main_list)
for list1 in main_list:
href = list1.get("href")
child_resp = requests.get(href)
child_resp.encoding = "utf-8"
child_page = BeautifulSoup(child_resp.text,"html.parser")
child_list = child_page.find("p",align="center").find("img")
img = child_list.get("src")
img_name = child_page.get("alt")
img_resp = requests.get(img)
img_resp.content
with open("F:\\img"+img_name,mode="wb") as f:
f.write(img_resp.content)
print("over",img_name)
time.sleep(2)
运行报错:requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, '远程主机强迫关闭了一个现有的连接。', None, 10054, None))我百度了下说是IP被封了,但是我换了IP还是不行那
这种有可能是网的问题 本帖最后由 591821661 于 2021-4-6 20:29 编辑
这种情况下大概率就是IP问题。我也碰到好多次 使用小飞机~
另外我推荐别使用requests下载图片。。
用urllib.request.urlretrieve(img_url,image_file_name)直接一步到位。
而且后续多线程爬图片也很方便
proxies={
'http':'127.0.0.1:1080',
'https':'127.0.0.1:1080'
}
resp = requests.get(url,headers = headers,proxies= proxies)
还有换个Header也是个不错的主意,你可以在看下自己浏览器是什么header 然后复制进去
本帖最后由 591821661 于 2021-4-6 20:39 编辑
很奇怪 我也跑出来也是这个问题 应该可以排除是网络问题
# -*- coding: utf-8 -*-
"""
@Time : 2021/4/6 20:31
@Author: 591821661
@File : Pyhelper.py
@Software: PyCharm
@Version : 0.0.1
@Comments:
"""
import requests
import socket
import urllib.request
from bs4 import BeautifulSoup
import time
url = "https://www.umei.cc/tupiandaquan/dongwutupian/"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
}
resp = requests.get(url,headers = headers)
resp.encoding = "utf-8"
# print(resp.text)
main_page = BeautifulSoup(resp.text,"html.parser")
main_list = main_page.find("div",class_="TypeList").find_all("a") #图片一级页面地址
# print(main_list)
for list1 in main_list:
time.sleep(0.2)
href = list1.get("href")
child_resp = requests.get(href,headers = headers)
child_resp.encoding = "utf-8"
child_page = BeautifulSoup(child_resp.text,"html.parser")
child_list = child_page.find("p",align="center").find("img")
img = child_list.get("src")
img_name = "Picture_Num_%d.jpg" % main_list.index(list1)
time.sleep(0.2)
try:
socket.setdefaulttimeout(15)# 设置15秒连接超时
urllib.request.urlretrieve(img, img_name)
except:
continue
问题解决,原因可能是你没有设置time_out的值 .下载图片超时了。
另外补充一句哈你爬的这种高清图 建议timeout 设为30 不然下载不完。
我这边 能够在15秒内下完的图 30张里面只有12张。 591821661 发表于 2021-4-6 20:56
问题解决,原因可能是你没有设置time_out的值 .下载图片超时了。
这个程序也是只能下载三张就报错了,和我代码报错的一样 代码小白liu 发表于 2021-4-7 21:52
这个程序也是只能下载三张就报错了,和我代码报错的一样
因为添加了try语句,就算报错也会继续运行。
如果需要把所有图片都下载下来,可以把延时设为30s,但这也不能保证都下载,和你本机的网络环境有关。
页:
[1]