首先找一个免费的代理网站
python 爬虫 代理池
获取请求地址
python 爬虫 代理池
查看网页源码,分析提取规则
python 爬虫 代理池
根据奇数偶数分别抓取xpath元素,再合并列表
python 爬虫 代理池
设置详细提取规则,提取ip地址和连接速度
python 爬虫 代理池
设置筛选条件,速度太慢的不要
python 爬虫 代理池
这里直接判断第一位是0,因为一秒以下会抓取到一个字符串比如0.177之类的

最后上结果
python 爬虫 代理池
一页爬下来,可用的大概70几个

以下是完整代码:

# 代理池
import requests
from lxml import etree

url = 'https://www.xicidaili.com/nn/'
headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36'
}
response = requests.get(url,headers=headers)  # 先抓一页 暂时够用了
eroot = etree.HTML(response.text)
ip_odd_element_list = eroot.xpath('//*[@id="ip_list"]/tr[@class="odd"]')
ip_even_element_list = eroot.xpath('//*[@id="ip_list"]/tr[@class=""]')
ip_element_raw = ip_odd_element_list + ip_even_element_list
# 获取所有ip元素列表,因为一会儿要从同一个元素中取出速度信息

ip_list = []
for ip_element in ip_element_raw:
    ip = ip_element.xpath('./td[2]/text()')
    speed = ip_element.xpath('./td[7]/div[1]/@title')
    if speed[0][0] == '0' :       # 只要连接速度在一秒以内的
        ip_list.append(ip)

print(ip_list)
print(len(ip_list))

相关文章: