在Python中,我们可以使用requests库来抓取代理IP,以下是一个简单的示例:

1、我们需要导入requests库,如果你还没有安装这个库,可以使用pip install requests命令来安装。
2、我们定义一个函数get_proxy,这个函数会从一个提供免费代理IP的网站抓取代理IP。
3、在这个函数中,我们使用requests.get方法来获取网页内容,然后使用BeautifulSoup库来解析HTML,找到代理IP和端口。
4、我们将抓取到的代理IP和端口返回。
注意:由于网站可能会更改其结构,所以这个代码可能需要根据实际情况进行调整。
import requests
from bs4 import BeautifulSoup
def get_proxy():
url = "https://www.xicidaili.com/nn/" # 这是一个提供免费代理IP的网站
headers = {"UserAgent": "Mozilla/5.0"}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'lxml')
ips = soup.select('tr')
for i in range(1, len(ips)):
ip_info = ips[i]
info_text = ip_info.text
ip = info_text.split("n")[2]
port = info_text.split("n")[3]
yield ":".join([ip, port])
测试
for proxy in get_proxy():
print(proxy)
这段代码会打印出从网站上抓取到的所有代理IP和端口,你可以将这些代理IP和端口设置到你的全局代理中。