python中设置代理的方法

1、设置http和https代理

 import requests
import time
from fake_useragent import UserAgent
if __name__ == '__main__':
    # 客户ip提取链接,每次提取1个,提取链接可以换成自己购买的
    url = 'http://api.shenlongip.com/ip?key=7wcdfdbd&pattern=text&count=1&need=1000&protocol=1'
    # 访问的目标地址
    targeturl = 'http://myip.ipip.net'
    response = requests.get(url)
    content = response.content.decode("utf-8").strip()
    print('提取IP:' + content)
    nowtime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
    print('提取IP时间:' + nowtime)
    sj = content.strip().split(":", 1)
    sj1 = sj[0]
    print("IP:", sj1)
    sj2 = sj[1]
    print("端口:", sj2)
    try:
        proxyMeta = "http://4cr9yf:ad675zh6@%(host)s:%(port)s" % {  # 账密验证,需要购买的代理套餐开通才可使用账密验证,此种情况无需加白名单
        # proxyMeta = "http://%(host)s:%(port)s" % {#白名单验证
            "host": sj1,
            "port": sj2,
        }
        print("代理1:", proxyMeta)
        proxysdata = {
            'http': proxyMeta,
            'https': proxyMeta
        }
        # 设置随机ua
        ua = UserAgent(verify_ssl=False)
        headers = {
            "user-agent": ua.random,
        }
        # print("请求头信息:",ua.random)
        start = int(round(time.time() * 1000))
        resp = requests.get(targeturl, headers=headers, timeout=20, proxies=proxysdata)
        costTime = int(round(time.time() * 1000)) - start
        print("耗时:" + str(costTime) + "ms")
        print("返回状态:",resp.status_code)
    except Exception as e:
        print(e)

2、设置socks5代理

import requests
import time
# 请求地址
if __name__ == '__main__':

    targetUrl = "http://myip.ipip.net"
    proxyHost = "43.248.79.156"
    proxyPort = "60949"

    # #pip install -U requests[socks]  socks5代理
    #白名单验证
    # proxyMeta = "socks5://%(host)s:%(port)s" % {
    #
    #     "host" : proxyHost,
    #
    #     "port" : proxyPort,
    #}
    #账号密码验证
    proxyMeta = "socks5://4cr9yf:ad675zh6@%(host)s:%(port)s" % {
        "host": proxyHost,
        "port": proxyPort,
    }
    proxies = {
        "http": proxyMeta,
        "https": proxyMeta
    }
    start = int(round(time.time() * 1000))
    resp = requests.get(targetUrl, proxies=proxies,timeout=25,allow_redirects=False)
    costTime = int(round(time.time() * 1000)) - start
    print("耗时:" + str(costTime) + "ms")
    print (resp.text)
    print("耗时:" + str(costTime) + "ms")
有需要国内、国外代理ip的可以私聊我,量大从惠

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

非凡的小羊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值