[英]I get TimeoutError: [WinError 10060] when I parsing my school website
# -*- 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
value=urllib.request.urlopen(url).read().decode('UTF8')
par='<title>(.+?)</title>'
result=re.findall(par,value)
print(result)
這是標題解析程序。 在像Google,Gmail網站這樣的解析時效果很好。 嘗試解析我的學校網站時出現錯誤。 在學校有問題嗎? 還是在我的代碼中?
您可以增加超時
碼:
value=urllib.request.urlopen(url,timeout=60).read().decode('UTF8')
使用Python請求( http://docs.python-requests.org/en/latest/ ),我可以下載http://jakjeon.icems.kr/main.do且沒有錯誤,盡管由於無法為Windows安裝朝鮮語代碼頁(949)。
這是腳本:
import requests
url='http://jakjeon.icems.kr/main.do'
r = requests.get(url)
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
print(r.text)
運行它打印:
200 # r.status_code
text/html; charset=UTF-8 # r.headers['content-type']
UTF-8 # r.encoding
后跟頁面的所有文本(r.text)
僅在將其代碼頁設置為65001(Unicode(UTF-8)后,才成功打印到Windows cmd.exe控制台,請參閱https://msdn.microsoft.com/zh-cn/library/windows/desktop/dd317756%28v = vs.85%29.aspx )。
嘗試將輸出重定向到文件會導致UnicodeEncodeError,因為我平台上文件的默認Windows編碼是代碼頁1252(ANSI拉丁語1;西歐語(Windows))。 這是嘗試打印到文件的錯誤消息:
Traceback (most recent call last):
File "URLDownloadDemo.py", line 12, in <module>
print(r.text)
File "C:\Anaconda3\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 600-601: character maps to <undefined>
然后,可以在https://goo.gl/Cyav17上獲得完整的cmd.exe控制台腳本,而在https://goo.gl/W4Sk9S上可以找到腳本的副本。
由於將輸出重定向到文件時出現編碼錯誤,我增強了腳本以使用UTF-8編碼將其輸出直接寫到文件中。 這是新的腳本:
import requests
url='http://jakjeon.icems.kr/main.do'
r = requests.get(url)
print(r.status_code)
print(r.headers['content-type'])
print(r.encoding)
fout = open('URLDownloadDemo.output.txt', mode='wt', encoding='UTF-8')
fout.write(r.text)
fout.close()
運行此命令可以很好地工作(沒有錯誤),並且輸出文件中包含的韓文字母符號與網頁源中的字母符號相同。
新腳本位於https://goo.gl/VJs2Na ,其輸出文件位於https://goo.gl/4BKe8C 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.