今天帶大家使用爬蟲(chóng)來(lái)獲取免費(fèi)的ip。
1. 打開(kāi)網(wǎng)站首頁(yè),可以看到總共有十頁(yè)數(shù)據(jù),總共100條ip記錄。咱們的目的很簡(jiǎn)單,就是要這100條ip和對(duì)應(yīng)端口號(hào)。完了我們?cè)偃ズY選那些ip是可用的。
http://www.ip3366.NET/?stype=1&page=1
2. 我們打開(kāi)瀏覽器模式模式分析頁(yè)面看到這些ip信息都位于tr標(biāo)簽內(nèi),所以我么可以使用xpath來(lái)獲取這些信息。
#獲取當(dāng)前頁(yè)面10個(gè)ip數(shù)據(jù)
ips = selector.xpath('//*[@id="list"]/table/tbody/tr')
print(len(ips))
'''
10
'''
3. 獲取到當(dāng)前頁(yè)面所有ip信息之后我們就可以使用for循環(huán)獲取tr標(biāo)簽內(nèi)部具體的ip和端口號(hào)。
# 獲取端口和IP
for ip in ips:
ip_num = ip.xpath('td[1]/text()').get() # ip
port_num = ip.xpath('td[2]/text()').get() # port
print(ip_num, port_num)
'''
49.70.151.180 3256
49.87.44.221 9999
42.177.142.239 9999
42.177.141.141 9999
42.176.134.43 9999
42.176.134.212 9999
49.71.142.114 9999
49.87.221.46 9999
49.87.221.120 9999
49.87.221.61 9999
'''
4. 接下來(lái)就使用for循環(huán)獲取十個(gè)頁(yè)面的100條數(shù)據(jù)。
for page in range(1, 10+1):
print(f'-------正在爬取第{page}頁(yè)數(shù)據(jù)-------')
url = f'http://www.ip3366.net/?stype=1&page={page}'
5. 測(cè)試可用性,現(xiàn)在所有的ip都已經(jīng)獲取到了,能不能用還是未知數(shù),所以我們?cè)囍羞@些ip登陸一下百度頁(yè)面,檢測(cè)其可用性。
for ip in ip_list:
try:
response = requests.get(url='https://www.baidu.com', proxies=ip, timeout=2)
if response.status_code == 200:
use_proxy.Append(ip)
except Exception as e:
print(f'當(dāng)前為第{count}個(gè)代理ip:', ip, '請(qǐng)求超時(shí), 檢測(cè)不合格!!!')
else:
print(f'當(dāng)前為第{count}個(gè)代理ip:', ip, '檢測(cè)通過(guò)')
檢測(cè)結(jié)果如下:
因?yàn)檫@些代理每小時(shí)都在更新,所以沒(méi)事多跑兩遍程序,總會(huì)獲取到你想的ip的。