[Python]自定义DNS的HttpClient

下面示例代码,自定义DNS,把baidu.com解析到了本机

from urllib3.util import connection

from urllib3 import connectionpool

_orig_create_connection = connection.create_connection


def your_dns_resolver(host):
    return "127.0.0.1"


def patched_create_connection(address, *args, **kwargs):
    host, port = address
    hostname = your_dns_resolver(host)
    return _orig_create_connection((hostname, port), *args, **kwargs)


connection.create_connection = patched_create_connection
conn = connectionpool.connection_from_url('http://baidu.com')
resp = conn.request('GET', 'http://baidu.com')
print(resp.data)

参考:https://stackoverflow.com/a/47645354/1926159

猜你喜欢

转载自blog.csdn.net/lbp0408/article/details/80402204