爬蟲Proxy(代理)的設置


爬蟲的時候默認會使用環境變量 http_proxy 來設置 HTTP Proxy。假如一個網站它會檢測某一段時間某個IP 的訪問次數,如果訪問次數過多,它會禁止你的訪問。所以你可以設置一些代理服務器來幫助你做工作,每隔一段時間換一個代理,這樣就不怕爬取大量數據的時候突然被封啦。
本文IP來自國內高匿免費HTTP代理IP__第1頁國內高匿 http://www.xicidaili.com/nn/
這一篇就主要講講怎么設置Proxy,上代碼!

from bs4 import BeautifulSoup
import requests
import random

def get_ip_list(url, headers):#得到該頁面的所有IP
    web_data = requests.get(url, headers=headers)#得到網頁響應web_data
    soup = BeautifulSoup(web_data.text, 'lxml')#解析網頁
    ips = soup.find_all('tr')
    ip_list = []
    for i in range(1, len(ips)):
        ip_info = ips[i]
        tds = ip_info.find_all('td')
        httptype=str.lower(tds[5].text)#把類型換成小寫
        ip_list.append(httptype+'://'+tds[1].text + ':' + tds[2].text)
    return ip_list
#從眾多的IP中隨機選一個出來使用
def get_random_ip(ip_list):
    proxy_ip = random.choice(ip_list)
    return proxy_ip

if __name__ == '__main__':
    url = 'http://www.xicidaili.com/nn/'
    #給請求指定一個請求頭來模擬瀏覽器
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'}
    ip_list = get_ip_list(url, headers=headers)#調用get_ip_list函數得到IP列表
    proxies = get_random_ip(ip_list)#調用函數get_random_ip從IP列表中隨機取用
    print(proxies)

  然后!把你得到的IP加進請求,就可以啦

proxies = {'http': 'http://114.97.184.251:808',
            'https': 'https://119.135.85.253:808' }
user_agent = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'
headers = {'User-Agent': user_agent}
htmlText = requests.get(url, headers=headers, timeout=3, proxies=proxies).text

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM