urllib2.urlopen raise urllib2.URLError

问题描述 投票:1回答:3

我正在做一个简单的工作来获取“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
3个回答
0
投票

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


0
投票

你的代码也适合我。

但是如果错误可能发生,则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

0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.