Force python mechanize/urllib2 to only use A requests?

后端 未结 4 1921
长发绾君心
长发绾君心 2020-12-14 04:29

Here is a related question but I could not figure out how to apply the answer to mechanize/urllib2: how to force python httplib library to use only A requests

Basica

4条回答
  •  隐瞒了意图╮
    2020-12-14 05:12

    Suffering from the same problem, here is an ugly hack (use at your own risk..) based on the information given by J.J. .

    This basically forces the family parameter of socket.getaddrinfo(..) to socket.AF_INET instead of using socket.AF_UNSPEC (zero, which is what seems to be used in socket.create_connection), not only for calls from urllib2 but should do it for all calls to socket.getaddrinfo(..):

    #--------------------
    # do this once at program startup
    #--------------------
    import socket
    origGetAddrInfo = socket.getaddrinfo
    
    def getAddrInfoWrapper(host, port, family=0, socktype=0, proto=0, flags=0):
        return origGetAddrInfo(host, port, socket.AF_INET, socktype, proto, flags)
    
    # replace the original socket.getaddrinfo by our version
    socket.getaddrinfo = getAddrInfoWrapper
    
    #--------------------
    import urllib2
    
    print urllib2.urlopen("http://python.org/").read(100)
    

    This works for me at least in this simple case.

提交回复
热议问题