添加User-Agent仍触发requests.exceptions.ConnectionError(10054)问题求解
解决添加User-Agent后仍出现ConnectionResetError的问题
我来帮你分析下这个问题——你已经配置了User-Agent但还是碰到requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(10054, ...)),这种情况其实很常见,因为网站的反爬机制远不止校验UA这一项。先看看你的代码:
import requests,bs4,pyperclip,webbrowser from urllib.request import quote movie='复仇者联盟' #movie name url='http://renrencili8.org/query/'+quote(movie)+'/1-0-0/' #url of the search page of the move headers={'user-agent':'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36'} #add a header in response to the anti-crawler scheme res=requests.get(url,headers=headers) #download the seach page of the movie bssearch=bs4.BeautifulSoup(res.text,'html.parser') #parse the page search_link=bssearch.select('.item dt sup a') # select the link by the tags of the page print(search_link) # I assumed a dict would be printed, showing the link
为什么加了User-Agent还会报错?
10054错误本质是对方服务器主动断开了你的连接,除了UA缺失,还有这些常见原因:
- 你的IP已经被网站封禁(有些网站对新IP的请求阈值极低,哪怕只发1-2次请求就会拉黑)
- 请求频率过高,触发了网站的频率限制
- 请求头不够完整,网站还在校验Referer、Accept等其他字段
- 网站需要Cookie验证,而单次请求无法维持会话状态
- 本地网络环境(运营商、防火墙、杀毒软件)拦截了目标网站的请求
具体解决方法
1. 先确认IP是否被封禁
打开浏览器直接访问你代码里的搜索URL,如果浏览器能正常打开,但代码请求失败,那基本可以确定你的IP被拉黑了。这时候需要用代理IP绕过:
# 替换成可用的代理IP和端口 proxies = { 'http': 'http://your-proxy-ip:port', 'https': 'http://your-proxy-ip:port' } res = requests.get(url, headers=headers, proxies=proxies)
注意:免费代理IP稳定性较差,建议使用付费代理服务。
2. 降低请求频率,模拟人类访问节奏
网站会检测短时间内的请求次数,你可以在请求前后添加延迟:
import time time.sleep(2) # 请求前等待2秒,模拟人类浏览间隔 res = requests.get(url, headers=headers)
3. 补全请求头信息
只加User-Agent可能不够,把浏览器真实的请求头字段补充完整,让请求更贴近真实用户:
headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.80 Safari/537.36', 'Referer': 'http://renrencili8.org/', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8', 'Accept-Language': 'zh-CN,zh;q=0.8,en;q=0.6', 'Connection': 'keep-alive' }
4. 使用会话保持Cookie
有些网站会给首次访问的用户设置Cookie,后续请求需要带上该Cookie才能正常响应,用requests.Session()维持会话:
session = requests.Session() session.headers.update(headers) # 先访问首页获取网站设置的Cookie session.get('http://renrencili8.org/') # 再访问搜索页 res = session.get(url)
5. 检查本地网络环境
试试切换到其他网络(比如手机热点),或者暂时关闭本地防火墙、杀毒软件,排查是否是网络层面的拦截导致连接被重置。
内容的提问来源于stack exchange,提问作者Chao Wang




