【问题标题】:urllib2.urlopen raise urllib2.URLErrorurllib2.urlopen 引发 urllib2.URLError
【发布时间】:2014-07-01 04:52:03
【问题描述】:

我正在做一个简单的工作来获得“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>

谁能告诉我这是怎么回事?

非常感谢!

【问题讨论】:

    标签: python urllib2


    【解决方案1】:

    听起来可能是网络问题。检查您是否具有一致的 Internet 连接(例如,在运行测试时不断 ping 适当的服务器)。只需运行您发布的代码,对我来说效果很好。

    【讨论】:

      【解决方案2】:

      你的代码也适合我。

      但如果 url 有一些字符,如“+=#”,则可能会发生错误,然后需要

      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
      

      【讨论】:

        【解决方案3】:

        这是网络问题,请确保您的互联网连接正常。

        【讨论】:

        • 你怎么可能知道...?
        猜你喜欢
        • 2018-01-26
        • 1970-01-01
        • 1970-01-01
        • 2012-12-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-11-18
        • 1970-01-01
        相关资源
        最近更新 更多