python爬取代理ip的示例
要寫爬蟲爬取大量的數(shù)據(jù),就會面臨ip被封的問題,雖然可以通過設置延時的方法來延緩對網(wǎng)站的訪問,但是一旦訪問次數(shù)過多仍然會面臨ip被封的風險,這時我們就需要用到動態(tài)的ip地址來隱藏真實的ip信息,如果做爬蟲項目,建議選取一些平臺提供的動態(tài)ip服務,引用api即可。目前國內有很多提供動態(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的示例的詳細內容,更多關于python爬取代理ip的資料請關注腳本之家其它相關文章!
相關文章
Python數(shù)據(jù)容器dict(字典)的實現(xiàn)
本文主要介紹了Python數(shù)據(jù)容器dict(字典)的實現(xiàn),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2023-02-02
解決Python?出現(xiàn)File?“<stdin>“,?line?1非語法錯誤的問題
這篇文章主要介紹了Python?出現(xiàn)File?“<stdin>“,?line?1非語法錯誤的解決辦法,本文給大家講解的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-03-03

