代码之家  ›  专栏  ›  技术社区  ›  froadie

为什么我不能让Python的urlopen()方法在Windows上工作?

  •  6
  • froadie  · 技术社区  · 16 年前

    为什么这个简单的Python代码不起作用?

    import urllib
    file = urllib.urlopen('http://www.google.com')
    print file.read()
    

    这是我得到的错误:

    Traceback (most recent call last):
      File "C:\workspace\GarchUpdate\src\Practice.py", line 26, in <module>
        file = urllib.urlopen('http://www.google.com')
      File "C:\Python26\lib\urllib.py", line 87, in urlopen
        return opener.open(url)
      File "C:\Python26\lib\urllib.py", line 206, in open
        return getattr(self, name)(url)
      File "C:\Python26\lib\urllib.py", line 345, in open_http
        h.endheaders()
      File "C:\Python26\lib\httplib.py", line 892, in endheaders
        self._send_output()
      File "C:\Python26\lib\httplib.py", line 764, in _send_output
        self.send(msg)
      File "C:\Python26\lib\httplib.py", line 723, in send
        self.connect()
      File "C:\Python26\lib\httplib.py", line 704, in connect
        self.timeout)
      File "C:\Python26\lib\socket.py", line 514, in create_connection
        raise error, msg
    IOError: [Errno socket error] [Errno 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond
    

    我试过用几页不同的纸,但我永远也找不到答案 urlopen

    4 回复  |  直到 12 年前
        1
  •  4
  •   user459872    6 年前

    你的代码不是这里的问题。

    这说明urllib.urlopen的python文档:


    从注册表的Internet设置中获取代理设置

        2
  •  3
  •   Aventador    12 年前

    如果可以更改某些代码行,请尝试使用urllib2。以秒为单位设置超时参数

    例如:

    urllib2.urlopen(http://www.abc.com/api, timeout=20)
    

    这里的连接持续时间更长。因此,如果您正在读取一个太大的XML文件,它可以避免不完整的读取。

    如果网络连接缓慢或突然中断,上述代码将永远无法工作。

        3
  •  1
  •   LoudNPossiblyWrong    16 年前

    我还记得有一次遇到类似的问题,我做的是刷新我的dns缓存

    (ipconfig/flushdns)并重新启动。它解决了我的问题。我想试试也无妨。

        4
  •  0
  •   Blue    7 年前

    import urllib.request
    
    proxies=urllib.request.ProxyHandler({'http':None})
    
    opener=urllib.request.build_opener(proxies)
    
    urllib.request.install_opener(opener)
    
    j=urllib.request.urlopen(url="https://google.com")
    
    k=j.read()
    
    print(k)