利用python爬虫(案例5)--X刺代理的小IP们
生活随笔
收集整理的這篇文章主要介紹了
利用python爬虫(案例5)--X刺代理的小IP们
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
學習筆記
爬取X刺代理的小IP們
學完代理,我們發現網上找的很多免費代理IP都用不了,所以這里寫一個簡單的測試小案例,爬取一下某代理IP網站的免費代理IP,再遍歷測試到底這些代理IP能不能用,哪些能用。
爬取步驟
獲取要爬取的代理IP網站地址(http://www.xicidaili.com/nn/)
爬取頁面內所有的代理IP及其端口號
測試代理IP
將可以用的代理IP存在一個csv文件里。
因為這個案例不是很復雜,所以我們就不寫怎么查看網頁源代碼,怎么寫Xpath,怎么研究URL特征這些步驟了,直接上代碼
python代碼
為了節省時間,我只測試了19個代理IP:
# -*- coding: utf-8 -*-import requests from lxml import etree from fake_useragent import UserAgent import time import csvclass IpSpider:def __init__(self):self.url = 'http://www.xicidaili.com/nn/'def get_ua(self):return UserAgent().randomdef get_page(self):headers = {'User-Agent':self.get_ua()}res = requests.get(self.url, headers = headers)html = res.content.decode('utf-8')print('url:', res.url)print('code:', res.status_code)#print(html)self.get_ip_list(html)def get_ip_list(self, html):html_parse = etree.HTML(html)xpath = '//table[@id="ip_list"]//tr'r_list = html_parse.xpath(xpath)#print(r_list)proxy_list = []for p in r_list[1:20]:my_ip = p.xpath('./td[2]/text()')[0]my_port = p.xpath('./td[3]/text()')[0]#print('代理IP:', my_ip)proxy_list.append({'http':'http://{}:{}'.format(my_ip, my_port), 'https':'https://{}:{}'.format(my_ip, my_port)})self.test_ip(proxy_list)def test_ip(self, proxy_list):useful_proxy = []for proxy in proxy_list:print(proxy)headers = {'User-Agent':self.get_ua()}try:res = requests.get(self.url, headers = headers,proxies = proxy,timeout = 4)#如果請求超過3秒沒有相應則默認該代理不能用except Exception as e:print('此代理IP無法使用......')else:useful_proxy.append(proxy)print(proxy)self.write_ip(useful_proxy)def write_ip(self, proxy_list):with open('./test/my_test_proxy.csv', 'w', newline = '') as f:writer = csv.writer(f)writer.writerow(['http', 'https'])for item in proxy_list:writer.writerow([item['http'], item['https']])def main(self):self.get_page()if __name__ == '__main__':start = time.time()spider = IpSpider()spider.main()end = time.time()print('執行時間:%.2f' % (end-start))部分結果:
此代理IP無法使用...... {'http': 'http://111.231.239.143:1081', 'https': 'https://111.231.239.143:1081'} 此代理IP無法使用...... {'http': 'http://115.223.64.38:8010', 'https': 'https://115.223.64.38:8010'} 此代理IP無法使用...... 執行時間:70.16可用的代理IP
我們打開存放可用代理IP的csv文件,看一下有哪些IP:
http,https http://125.126.117.30:60004,https://125.126.117.30:60004 http://125.126.113.184:60004,https://125.126.113.184:60004 http://112.16.217.191:808,https://112.16.217.191:808好了,這個小案例完結…
總結
以上是生活随笔為你收集整理的利用python爬虫(案例5)--X刺代理的小IP们的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 斐讯 FIR302C 无线路由器无线桥接
- 下一篇: TP-Link TL-WDR6500 V