Python爬取云代理IP并筛选保存到文件
以下是一个简单的Python程序,可用于爬取云代理网站的代理IP,并将其筛选后保存到文件中:
import requests
from bs4 import BeautifulSoup
# 要爬取的网站
url = 'http://www.ip3366.net/free/'
# 请求网站
response = requests.get(url)
# 解析HTML
soup = BeautifulSoup(response.text, 'html.parser')
# 找到代理IP所在的表格
table = soup.find('table', attrs={'id': 'list'})
# 找到所有的行
rows = table.find_all('tr')
# 遍历每行,获取代理IP和端口号
proxies = []
for row in rows[1:]:
cols = row.find_all('td')
ip = cols[0].text.strip()
port = cols[1].text.strip()
proxies.append(f'{ip}:{port}')
# 过滤掉无效的代理IP
proxies = [p for p in proxies if ':' in p]
# 将有效的代理IP写入文件
with open('proxies.txt', 'w') as f:
for p in proxies:
f.write(p + '\n')
该程序使用requests库和BeautifulSoup库来请求和解析HTML,找到代理IP所在的表格,并获取每行中的代理IP和端口号。然后,它过滤掉无效的代理IP,并将有效的代理IP写入名为'proxies.txt'的文件中。
原文地址: https://www.cveoy.top/t/topic/ndrJ 著作权归作者所有。请勿转载和采集!