我使用python 3.4和我的腳本是這樣的:蟒蛇 - 網頁抓取BeautifulSoup和urllib的
import urllib
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
from bs4 import BeautifulSoup
url = "http://www.embassy-worldwide.com/"
headers={'User-Agent': 'Mozilla/5.0'}
#req = Request(url, headers)
try:
req = urllib.request.Request(url, headers)
#print (req)
except HTTPError as e:
print('Error code: ', e.code)
except URLError as e:
print('Reason: ', e.reason)
else:
print('good!')
print (req)
#html = urllib.request.urlopen(req)
with urllib.request.urlopen(req) as response:
html = response.read()
print(html)
上述導致錯誤代碼:
ValueError異常:內容長度應指定可以迭代的數據{'User-Agent':'Mozilla/5.0'}
如何獲取html代碼然後遍歷標籤以獲取所有國家的列表?
請使用'urllib3'。 – 2016-03-05 12:47:34
urllib有什麼不好?你能舉一個例子作爲解決方案嗎? –
'urllib'有許多已知的缺陷,它們在'urllib2'和'urllib3'(以及'request',它基於'urllib3')中被修復。如果沒有任何好的指示,urllib可能會隨機失敗(特別是在高負載的情況下)。此外,在這個庫中,在社區中,使用最新版本來防止舊版本可能會自動解決的問題是很常見的。 – 2016-03-05 12:53:26