gpt4 book ai didi

python - "ConnectionResetError"我该怎么办?

转载 作者:太空宇宙 更新时间:2023-11-03 17:32:39 25 4
gpt4 key购买 nike

# -*- 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)

超时错误消失了。但出现ConnectionResetError。这是什么错误?是服务器问题吗?那跟我解决不了吗?

最佳答案

포기하지마세요!不要放弃!

某些网站需要特定的 HTTP header ,在本例中为 User-agent。因此,您需要在请求中设置此 header 。

像这样更改您的请求(代码的 17 - 20 行)

# 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')

您可以将“Python urllib test”更改为您想要的任何内容。几乎每个服务器都使用 User-agent 进行统计。

最后,考虑使用适当的空格、空行、注释来使代码更具可读性。这对你有好处。

<小时/>

更多阅读:

关于python - "ConnectionResetError"我该怎么办?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31673344/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com