溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Python爬蟲怎么實(shí)現(xiàn)搭建代理ip池

發(fā)布時(shí)間:2022-06-22 09:28:32 來源:億速云 閱讀:244 作者:iii 欄目:開發(fā)技術(shù)

這篇“Python爬蟲怎么實(shí)現(xiàn)搭建代理ip池”文章的知識(shí)點(diǎn)大部分人都不太理解,所以小編給大家總結(jié)了以下內(nèi)容,內(nèi)容詳細(xì),步驟清晰,具有一定的借鑒價(jià)值,希望大家閱讀完這篇文章能有所收獲,下面我們一起來看看這篇“Python爬蟲怎么實(shí)現(xiàn)搭建代理ip池”文章吧。

一、User-Agent

在發(fā)送請(qǐng)求的時(shí)候,通常都會(huì)做一個(gè)簡單的反爬。這時(shí)可以用fake_useragent模塊來設(shè)置一個(gè)請(qǐng)求頭,用來進(jìn)行偽裝成瀏覽器,下面兩種方法都可以。

from fake_useragent import UserAgent
headers = {
        # 'User-Agent': UserAgent().random #常見瀏覽器的請(qǐng)求頭偽裝(如:火狐,谷歌)
        'User-Agent': UserAgent().Chrome #谷歌瀏覽器
    }

Python爬蟲怎么實(shí)現(xiàn)搭建代理ip池

二、發(fā)送請(qǐng)求

response = requests.get(url='http://www.ip3366.net/free/', headers=request_header())
        # text = response.text.encode('ISO-8859-1')
        # print(text.decode('gbk'))

三、解析數(shù)據(jù)

我們只需要解析出ip、port即可。

Python爬蟲怎么實(shí)現(xiàn)搭建代理ip池

Python爬蟲怎么實(shí)現(xiàn)搭建代理ip池

使用xpath解析(個(gè)人很喜歡用)(當(dāng)然還有很多的解析方法,如:正則,css選擇器,BeautifulSoup等等)。

	#使用xpath解析,提取出數(shù)據(jù)ip,端口
        html = etree.HTML(response.text)
        tr_list = html.xpath('/html/body/div[2]/div/div[2]/table/tbody/tr')
        for td in tr_list:
            ip_ = td.xpath('./td[1]/text()')[0] #ip
            port_ = td.xpath('./td[2]/text()')[0]  #端口
            proxy = ip_ + ':' + port_   #115.218.5.5:9000

四、構(gòu)建ip代理池,檢測ip是否可用

#構(gòu)建代理ip
	proxy = ip + ':' + port
	proxies = {
        "http": "http://" + proxy,
        "https": "http://" + proxy,
        # "http": proxy,
        # "https": proxy,
    }
    try:
        response = requests.get(url='https://www.baidu.com/',headers=request_header(),proxies=proxies,timeout=1) #設(shè)置timeout,使響應(yīng)等待1s
        response.close()
        if response.status_code == 200:
            print(proxy, '\033[31m可用\033[0m')
        else:
            print(proxy, '不可用')
    except:
        print(proxy,'請(qǐng)求異常')

五、完整代碼

import requests                         #導(dǎo)入模塊
from lxml import etree
from fake_useragent import UserAgent
#簡單的反爬,設(shè)置一個(gè)請(qǐng)求頭來偽裝成瀏覽器
def request_header():
    headers = {
        # 'User-Agent': UserAgent().random #常見瀏覽器的請(qǐng)求頭偽裝(如:火狐,谷歌)
        'User-Agent': UserAgent().Chrome #谷歌瀏覽器
    }
    return headers
'''
創(chuàng)建兩個(gè)列表用來存放代理ip
'''
all_ip_list = []  #用于存放從網(wǎng)站上抓取到的ip
usable_ip_list = [] #用于存放通過檢測ip后是否可以使用

#發(fā)送請(qǐng)求,獲得響應(yīng)
def send_request():
    #爬取7頁,可自行修改
    for i in range(1,8): 
        print(f'正在抓取第{i}頁……')
        response = requests.get(url=f'http://www.ip3366.net/free/?page={i}', headers=request_header())
        text = response.text.encode('ISO-8859-1')
        # print(text.decode('gbk'))
        #使用xpath解析,提取出數(shù)據(jù)ip,端口
        html = etree.HTML(text)
        tr_list = html.xpath('/html/body/div[2]/div/div[2]/table/tbody/tr')
        for td in tr_list:
            ip_ = td.xpath('./td[1]/text()')[0] #ip
            port_ = td.xpath('./td[2]/text()')[0]  #端口
            proxy = ip_ + ':' + port_   #115.218.5.5:9000
            all_ip_list.append(proxy)
            test_ip(proxy)      #開始檢測獲取到的ip是否可以使用
    print('抓取完成!')
    print(f'抓取到的ip個(gè)數(shù)為:{len(all_ip_list)}')
    print(f'可以使用的ip個(gè)數(shù)為:{len(usable_ip_list)}')
    print('分別有:\n', usable_ip_list)
#檢測ip是否可以使用
def test_ip(proxy):
    #構(gòu)建代理ip
    proxies = {
        "http": "http://" + proxy,
        "https": "http://" + proxy,
        # "http": proxy,
        # "https": proxy,
    }
    try:
        response = requests.get(url='https://www.baidu.com/',headers=request_header(),proxies=proxies,timeout=1) #設(shè)置timeout,使響應(yīng)等待1s
        response.close()
        if response.status_code == 200:
            usable_ip_list.append(proxy)
            print(proxy, '\033[31m可用\033[0m')
        else:
            print(proxy, '不可用')
    except:
        print(proxy,'請(qǐng)求異常')
if __name__ == '__main__':
    send_request()

以上就是關(guān)于“Python爬蟲怎么實(shí)現(xiàn)搭建代理ip池”這篇文章的內(nèi)容,相信大家都有了一定的了解,希望小編分享的內(nèi)容對(duì)大家有幫助,若想了解更多相關(guān)的知識(shí)內(nèi)容,請(qǐng)關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請(qǐng)聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI