要寫爬蟲爬取大量的數據,就會面臨ip被封的問題,雖然可以通過設置延時的方法來延緩對網站的訪問,但是一旦訪問次數過多仍然會面臨ip被封的風險,這時我們就需要用到動態的ip地址來隱藏真實的ip信息,如果做爬蟲項目,建議選取一些平臺提供的動態ip服務,引用api即可。目前國內有很多提供動態ip的平臺,普遍價格不菲,而對于只想跑個小項目用來學習的話可以參考下本篇文章。
簡述
本篇使用簡單的爬蟲程序來爬取免費ip網站的ip信息并生成json文檔,存儲可用的ip地址,寫其它爬取項目的時候可以從生成的json文檔中提取ip地址使用,為了確保使用的ip地址的有效性,建議對json文檔中的ip現爬現用,并且在爬取時對ip有效性的時間進行篩選,只爬取時長較長、可用的ip地址存儲。
實現
使用平臺https://www.xicidaili.com/nn/來作為數據源,通過對http://www.baidu.com/的相應來判斷ip的可使用性。引用lxml模塊來對網頁數據進行提取,當然也可以使用re模塊來進行匹配提取,這里只使用lxml模塊對數據進行提取。
訪問https://www.xicidaili.com/nn/數據源,并且啟動Fiddler對瀏覽器數據進行監聽,我這里瀏覽器采用的是Proxy SwitchyOmega插件來配合Fiddler進行使用,在Fiddler找到/nn/*數據查看User-Agent信息并復制下來作為我們訪問的頭文件。如圖:
引入模塊
1
2
3
4
|
import requests from lxml import etree import time import json |
獲取所有數據
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
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 |
對數據進行篩選:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
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) |
運行程序:
1
2
3
4
5
|
if __name__ = = '__main__' : for i in range ( 1 , 11 ): #選取前十頁數據使用 proxy_list = get_all_proxy(i) time.sleep( 20 ) print (valid_proxy_list) |
生成的json文件:
以上就是python爬取代理ip的示例的詳細內容,更多關于python爬取代理ip的資料請關注服務器之家其它相關文章!
原文鏈接:https://www.cnblogs.com/supershuai/p/12297312.html