Python &引用;ConnectionResetError“;我该怎么办? #-*-编码:UTF-8-*- 导入urllib.request 进口稀土 导入操作系统 操作系统(“cls”) url=输入(“url链接:”) 如果(url[0:8]=“https://”): url=url[:4]+url[5:] 如果(url[0:7]!=“http:/”): url=“http://”+url 尝试: 尝试: value=urllib.request.urlopen(url,超时=60.read().decode('cp949')) 除UNICEDECODEERROR外: value=urllib.request.urlopen(url,超时=60).read().decode('UTF8') par='(.+?)' 结果=关于findall(标准件,数值) 打印(结果) 除ConnectionResetError为e外: 打印(e)
时间错误消失了。但是ConnectionResetError出现了。这个错误是什么?是服务器问题吗?所以我无法解决这个问题?포기하지 마세요! 不要放弃 有些网站需要特定的HTTP头,在本例中为Python &引用;ConnectionResetError“;我该怎么办? #-*-编码:UTF-8-*- 导入urllib.request 进口稀土 导入操作系统 操作系统(“cls”) url=输入(“url链接:”) 如果(url[0:8]=“https://”): url=url[:4]+url[5:] 如果(url[0:7]!=“http:/”): url=“http://”+url 尝试: 尝试: value=urllib.request.urlopen(url,超时=60.read().decode('cp949')) 除UNICEDECODEERROR外: value=urllib.request.urlopen(url,超时=60).read().decode('UTF8') par='(.+?)' 结果=关于findall(标准件,数值) 打印(结果) 除ConnectionResetError为e外: 打印(e),python,Python,时间错误消失了。但是ConnectionResetError出现了。这个错误是什么?是服务器问题吗?所以我无法解决这个问题?포기하지 마세요! 不要放弃 有些网站需要特定的HTTP头,在本例中为User-agent。因此,您需要在请求中设置此标头 像这样更改您的请求(代码的17-20行) 您可以将“Python urllib test”更改为您想要的任何内容。几乎每个服务器都使用用户代理进行统计 最后,考虑使用适当的空白、空白行、注释来提高代码的可读性。这对你有好处 更多阅读: -了解什么是
User-agent
。因此,您需要在请求中设置此标头
像这样更改您的请求(代码的17-20行)
您可以将“Python urllib test”
更改为您想要的任何内容。几乎每个服务器都使用用户代理
进行统计
最后,考虑使用适当的空白、空白行、注释来提高代码的可读性。这对你有好处
更多阅读:
- -了解什么是用户代理标头
- -始终阅读文档。链接到
部分urllib.request.request
# -*- coding: UTF-8 -*-
import urllib.request
import re
import os
os.system("cls")
url=input("Url Link : ")
if(url[0:8]=="https://"):
url=url[:4]+url[5:]
if(url[0:7]!="http://"):
url="http://"+url
try :
try :
value=urllib.request.urlopen(url,timeout=60).read().decode('cp949')
except UnicodeDecodeError :
value=urllib.request.urlopen(url,timeout=60).read().decode('UTF8')
par='<title>(.+?)</title>'
result=re.findall(par,value)
print(result)
except ConnectionResetError as e:
print(e)
# Make request object
request = urllib.request.Request(url, headers={"User-agent": "Python urllib test"})
# Open url using request object
response = urllib.request.urlopen(request, timeout=60)
# read response
data = response.read()
# decode your value
try:
value = data.decode('CP949')
except UnicodeDecodeError:
value = data.decode('UTF-8')