python爬取代理ip的示例
要寫爬蟲爬取大量的數(shù)據(jù),就會面臨ip被封的問題,雖然可以通過設(shè)置延時的方法來延緩對網(wǎng)站的訪問,但是一旦訪問次數(shù)過多仍然會面臨ip被封的風險,這時我們就需要用到動態(tài)的ip地址來隱藏真實的ip信息,如果做爬蟲項目,建議選取一些平臺提供的動態(tài)ip服務,引用api即可。目前國內(nèi)有很多提供動態(tài)ip的平臺,普遍價格不菲,而對于只想跑個小項目用來學習的話可以參考下本篇文章。
簡述
本篇使用簡單的爬蟲程序來爬取免費ip網(wǎng)站的ip信息并生成json文檔,存儲可用的ip地址,寫其它爬取項目的時候可以從生成的json文檔中提取ip地址使用,為了確保使用的ip地址的有效性,建議對json文檔中的ip現(xiàn)爬現(xiàn)用,并且在爬取時對ip有效性的時間進行篩選,只爬取時長較長、可用的ip地址存儲。
實現(xiàn)
使用平臺https://www.xicidaili.com/nn/來作為數(shù)據(jù)源,通過對http://www.baidu.com/的相應來判斷ip的可使用性。引用lxml模塊來對網(wǎng)頁數(shù)據(jù)進行提取,當然也可以使用re模塊來進行匹配提取,這里只使用lxml模塊對數(shù)據(jù)進行提取。
訪問https://www.xicidaili.com/nn/數(shù)據(jù)源,并且啟動Fiddler對瀏覽器數(shù)據(jù)進行監(jiān)聽,我這里瀏覽器采用的是Proxy SwitchyOmega插件來配合Fiddler進行使用,在Fiddler找到/nn/*數(shù)據(jù)查看User-Agent信息并復制下來作為我們訪問的頭文件。如圖:
引入模塊
import requests from lxml import etree import time import json
獲取所有數(shù)據(jù)
def get_all_proxy(page): url = 'https://www.xicidaili.com/nn/%s'%page headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36', } response = requests.get(url, headers=headers) html_ele = etree.HTML(response.text) ip_eles = html_ele.xpath('//table[@id="ip_list"]/tr/td[2]/text()') port_ele = html_ele.xpath('//table[@id="ip_list"]/tr/td[3]/text()') print(ip_eles) proxy_list = [] for i in range(0,len(ip_eles)): check_all_proxy(ip_eles[i],port_ele[i]) return proxy_list
對數(shù)據(jù)進行篩選:
def check_all_proxy(host,port): type = 'http' proxies = {} proxy_str = "%s://@%s:%s" % (type, host, port) valid_proxy_list = [] url = 'http://www.baidu.com/' proxy_dict = { 'http': proxy_str, 'https': proxy_str } try: start_time = time.time() response = requests.get(url, proxies=proxy_dict, timeout=5) if response.status_code == 200: end_time = time.time() print('代理可用:' + proxy_str) print('耗時:' + str(end_time - start_time)) proxies['type'] = type proxies['host'] = host proxies['port'] = port proxiesJson = json.dumps(proxies) with open('verified_y.json', 'a+') as f: f.write(proxiesJson + '\n') print("已寫入:%s" % proxy_str) valid_proxy_list.append(proxy_str) else: print('代理超時') except: print('代理不可用--------------->'+proxy_str)
運行程序:
if __name__ == '__main__': for i in range(1,11): #選取前十頁數(shù)據(jù)使用 proxy_list = get_all_proxy(i) time.sleep(20) print(valid_proxy_list)
生成的json文件:
以上就是python爬取代理ip的示例的詳細內(nèi)容,更多關(guān)于python爬取代理ip的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
python的dict,set,list,tuple應用詳解
這篇文章主要介紹了python的dict,set,list,tuple應用詳解,需要的朋友可以參考下2014-07-07Python實現(xiàn)快速排序算法及去重的快速排序的簡單示例
quick sort快速排序是一種再基礎(chǔ)不過的排序算法,使用Python代碼寫起來相當簡潔,這里我們就來看一下Python實現(xiàn)快速排序算法及去重的快速排序的簡單示例:2016-06-06python 通過SMSActivateAPI 獲取驗證碼的步驟
這篇文章主要介紹了python 通過SMSActivateAPI 如何獲取驗證碼,本文分步驟給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-05-05