报错求助 无法下载res.text文档
import requestsdef get_url(url):
headers={'user-agent':'Mozilla/5.0(Windows NT 10.0;WOW64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.98 Safari/537.36'}
res=requests.get(url,headers=headers)
return res
def main():
url=input('请输入地址:')
res=get_url(url)
with open ('res.txt','w',encoding='utf-8') as file:
file.write(res.text)
if__name__ == '__main__':
main()
import requests
def getRes(url):
try:
res = requests.get(url, timeout=30)
res.raise_for_status()# 如果状态不是200,即未成功获得数据则引发异常
res.encoding = res.apparent_encoding
return res
except:
return '爬取异常' + url
def main():
while True:
url = input('请输入正确的url地址(例如https://www.baidu.com):')
if url[:7] != 'http://' and url[:8] != 'https://':
print('请输入正确的url地址,例如https://www.baidu.com')
continue
else:
break
res = getRes(url)
if type(res) == type('error'):
print(res)
else:
with open('./res.txt', 'w', encoding='utf-8') as fp:
fp.write(res.text)
if __name__ == '__main__':
main()
页:
[1]