requests使用代理IP访问

本文介绍使用python requests包请求网站时,使用代理IP访问的方法
使用到的资源:

1.获取免费代理的网站:http://www.xicidaili.com/
2.获取当前访问的IP地址:https://www.ipip.net/
我们通过访问ipip.net网站,获取当前访问使用的IP地址,来验证我们的代理是否成功

实现代码:

import requests
import ssl 
from lxml import etree
ssl._create_default_https_context = ssl._create_unverified_context 

#获取当前访问使用的IP地址网站
url="https://www.ipip.net/"

#设置代理,从西刺免费代理网站上找出一个可用的代理IP
proxies={'https':'101.236.54.97:8866'} #此处也可以通过列表形式,设置多个代理IP,后面通过random.choice()随机选取一个进行使用

#使用代理IP进行访问
res=requests.get(url,proxies=proxies,timeout=10)
status=res.status_code # 状态码
print(status)
content=res.text
html=etree.HTML(content)
ip=html.xpath('//ul[@class="inner"]/li[1]/text()')[0]
print("当前请求IP地址为:"+ip)

猜你喜欢

转载自blog.csdn.net/d1240673769/article/details/80757045