urllib2.urlopen raise urllib2.URLError

时间:2014-07-01 04:52:03

标签: python urllib2

我正在轻松完成“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>
谁能告诉我发生了什么事?

非常感谢!

2 个答案:

答案 0 :(得分:0)

听起来可能是网络问题。检查您是否具有一致的Internet连接(例如,在运行测试时连续ping适当的服务器)。只需运行您发布的代码并为我完美地工作。

答案 1 :(得分:0)

你的代码也适合我。

但是错误可能发生在这种情况下,网址有一些字符,如&#34; + =#&#34;然后需要

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

或者您也可以使用请求。

response =requests.post(url)
print response.content 

print response.text