我使用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