本文小編為大家詳細(xì)介紹“怎么用python爬蟲建立免費(fèi)ip代理池”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“怎么用python爬蟲建立免費(fèi)ip代理池”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。
作為一家“創(chuàng)意+整合+營(yíng)銷”的成都網(wǎng)站建設(shè)機(jī)構(gòu),我們?cè)跇I(yè)內(nèi)良好的客戶口碑。創(chuàng)新互聯(lián)公司提供從前期的網(wǎng)站品牌分析策劃、網(wǎng)站設(shè)計(jì)、成都做網(wǎng)站、成都網(wǎng)站建設(shè)、創(chuàng)意表現(xiàn)、網(wǎng)頁制作、系統(tǒng)開發(fā)以及后續(xù)網(wǎng)站營(yíng)銷運(yùn)營(yíng)等一系列服務(wù),幫助企業(yè)打造創(chuàng)新的互聯(lián)網(wǎng)品牌經(jīng)營(yíng)模式與有效的網(wǎng)絡(luò)營(yíng)銷方法,創(chuàng)造更大的價(jià)值。
本代碼包括ip的爬取,檢測(cè)是否可用,可用保存,通過函數(shù)get_proxies可以獲得ip,如:{‘HTTPS’: ‘106.12.7.54:8118’}
下面放上源代碼,并詳細(xì)注釋:
import requests
from lxml import etree
from requests.packages import urllib3
import random, time
urllib3.disable_warnings()
def spider(pages, max_change_porxies_times=300):
"""
抓取 XiciDaili.com 的 http類型-代理ip-和端口號(hào)
將所有抓取的ip存入 raw_ips.csv 待處理, 可用 check_proxies() 檢查爬取到的代理ip是否可用
-----
:param pages:要抓取多少頁
:return:無返回
"""
s = requests.session()
s.trust_env = False
s.verify = False
urls = 'https://www.xicidaili.com/nn/{}'
proxies = {}
try_times = 0
for i in range(pages):
url = urls.format(i + 1)
s.headers = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9',
'Connection': 'keep-alive',
'Referer': urls.format(i if i > 0 else ''),
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.75 Safari/537.36'}
while True:
content = s.get(url, headers=s.headers, proxies=proxies)
time.sleep(random.uniform(1.5, 4)) # 每讀取一次頁面暫停一會(huì),否則會(huì)被封
if content.status_code == 503: # 如果503則ip被封,就更換ip
proxies = get_proxies()
try_times += 1
print(f'第{str(try_times):0>3s}次變更,當(dāng)前{proxies}')
if try_times > max_change_porxies_times:
print('超過最大嘗試次數(shù),連接失敗!')
return -1
continue
else:
break # 如果返回碼是200 ,就跳出while循環(huán),對(duì)爬取的頁面進(jìn)行處理
print(f'正在抓取第{i+1}頁數(shù)據(jù),共{pages}頁')
for j in range(2, 102): # 用簡(jiǎn)單的xpath提取http,host和port
tree = etree.HTML(content.text)
http = tree.xpath(f'//table[@id="ip_list"]/tr[{j}]/td[6]/text()')[0]
host = tree.xpath(f'//table[@id="ip_list"]/tr[{j}]/td[2]/text()')[0]
port = tree.xpath(f'//table[@id="ip_list"]/tr[{j}]/td[3]/text()')[0]
check_proxies(http, host, port) # 檢查提取的代理ip是否可用
def check_proxies(http, host, port, test_url='http://www.baidu.com'):
"""
檢測(cè)給定的ip信息是否可用
根據(jù)http,host,port組成proxies,對(duì)test_url進(jìn)行連接測(cè)試,如果通過,則保存在 ips_pool.csv 中
:param http: 傳輸協(xié)議類型
:param host: 主機(jī)
:param port: 端口號(hào)
:param test_url: 測(cè)試ip
:return: None
"""
proxies = {http: host + ':' + port}
try:
res = requests.get(test_url, proxies=proxies, timeout=2)
if res.status_code == 200:
print(f'{proxies}檢測(cè)通過')
with open('ips_pool.csv', 'a+') as f:
f.write(','.join([http, host, port]) + '\n')
except Exception as e: # 檢測(cè)不通過,就不保存,別讓報(bào)錯(cuò)打斷程序
print(e)
def check_local_ip(fn, test_url):
"""
檢查存放在本地ip池的代理ip是否可用
通過讀取fn內(nèi)容,加載每一條ip對(duì)test_url進(jìn)行連接測(cè)試,鏈接成功則儲(chǔ)存在 ips_pool.csv 文件中
:param fn: filename,儲(chǔ)存代理ip的文件名
:param test_url: 要進(jìn)行測(cè)試的ip
:return: None
"""
with open(fn, 'r') as f:
datas = f.readlines()
ip_pools = []
for data in datas:
# time.sleep(1)
ip_msg = data.strip().split(',')
http = ip_msg[0]
host = ip_msg[1]
port = ip_msg[2]
proxies = {http: host + ':' + port}
try:
res = requests.get(test_url, proxies=proxies, timeout=2)
if res.status_code == 200:
ip_pools.append(data)
print(f'{proxies}檢測(cè)通過')
with open('ips_pool.csv', 'a+') as f:
f.write(','.join([http, host, port]) + '\n')
except Exception as e:
print(e)
continue
def get_proxies(ip_pool_name='ips_pool.csv'):
"""
從ip池獲得一個(gè)隨機(jī)的代理ip
:param ip_pool_name: str,存放ip池的文件名,
:return: 返回一個(gè)proxies字典,形如:{'HTTPS': '106.12.7.54:8118'}
"""
with open(ip_pool_name, 'r') as f:
datas = f.readlines()
ran_num = random.choice(datas)
ip = ran_num.strip().split(',')
proxies = {ip[0]: ip[1] + ':' + ip[2]}
return proxies
if __name__ == '__main__':
t1 = time.time()
spider(pages=3400)
t2 = time.time()
print('抓取完畢,時(shí)間:', t2 - t1)
# check_local_ip('raw_ips.csv','http://www.baidu.com')
讀到這里,這篇“怎么用python爬蟲建立免費(fèi)ip代理池”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。
文章名稱:怎么用python爬蟲建立免費(fèi)ip代理池
轉(zhuǎn)載來于:http://aaarwkj.com/article26/pjdicg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計(jì)公司、ChatGPT、用戶體驗(yàn)、自適應(yīng)網(wǎng)站、面包屑導(dǎo)航
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)