首页 > 编程语言 > 详细

Python Requests IP直连

时间:2019-04-19 18:42:35      阅读:122      评论:0      收藏:0      [点我收藏+]
import re
import requests
from urllib3.util import connection

_orig_create_connection = connection.create_connection


def patched_create_connection(address, *args, **kwargs):
    s = str(address[1])
    if len(s) == 18:
        port = int(s[1:6])
        ip = str(int(s[6:9])) + ‘.‘ + str(int(s[9:12])) + ‘.‘ + str(int(s[12:15])) + ‘.‘ + str(int(s[15:18]))
    else:
        port = address[1]
        ip = address[0]
    return _orig_create_connection((ip, port), *args, **kwargs)


connection.create_connection = patched_create_connection


def get(url, ip, params=None, **kwargs):
    str_port = ‘100080‘
    str_ip = ‘‘
    for ipe in ip.split(‘.‘):
        str_ip += ipe.zfill(3)
    mc = re.match(r‘^((https?)://([^/:]+))(?::(\d+))?‘, url, re.I)
    if mc:
        if mc.group(2):
            if mc.group(2).lower() == ‘https‘:
                str_port = ‘100443‘
        if mc.group(3):
            if ‘headers‘ not in kwargs:
                kwargs[‘headers‘] = {}
            if ‘host‘ not in kwargs[‘headers‘]:
                kwargs[‘headers‘][‘host‘] = mc.group(3)
        if mc.group(4):
            str_port = ‘1‘ + mc.group(4).zfill(5)
        url = url.replace(mc.group(0), mc.group(1) + ‘:‘ + str_port + str_ip, 1)
    return requests.get(url, params=params, **kwargs)

  

Python Requests IP直连

原文:https://www.cnblogs.com/j4s0n/p/10737788.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!