urllib2.urlopen 引发 urllib2.URLError
我正在做一个简单的工作,想要获取这个页面:"http://search.jd.com/Search?keyword=%E5%A5%87%E7%9F%B3&enc=utf-8"
所以我的Python代码是:
# -*- coding: utf-8 -*-
import sys, codecs
import urllib, urllib2
url = "http://search.jd.com/Search?keyword=%E5%A5%87%E7%9F%B3&enc=utf-8"
print url
page=urllib2.urlopen(url).read()
print page
但是我得到了
Traceback (most recent call last):
File "tmp.py", line 15, in <module>
page=urllib2.urlopen(url).read()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
return _opener.open(url, data, timeout)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 404, in open
response = self._open(req, data)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 422, in _open
'_open', req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
result = func(*args)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1214, in http_open
return self.do_open(httplib.HTTPConnection, req)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1184, in do_open
raise URLError(err)
urllib2.URLError: <urlopen error [Errno 8] nodename nor servname provided, or not known>
有没有人能告诉我发生了什么事?
非常感谢!
3 个回答
1
这是网络问题,请确保你连接的是一个正常的互联网。
1
你的代码在我这儿也运行得很好。
不过,如果网址里有一些特殊字符,比如“+=#”,就可能会出现错误,这时候就需要
s = "http://search.jd.com/Search?keyword=%E5%A5%87%E7%9F%B3&enc=utf-8"
my_url = urllib2.quote(s.encode("utf8"))
page=urllib2.urlopen(my_url).read()
print page
另外,你也可以使用requests库。
response =requests.post(url)
print response.content
或者
print response.text
1
听起来可能是网络的问题。检查一下你的网络连接是否稳定,比如在运行测试的时候,可以持续地 ping 一个合适的服务器。刚刚我运行了你发的代码,结果一切都很好。