scrapy代理的設置


scrapy代理的設置

在我的上一篇文章介紹了scrapy下載器中間件的使用,這里的scrapyIP的代理就是用這個原理實現的,重寫了下載器中間件的process_request(self,request,spider)這個函數,這個函數的主要作用就是對request進行處理。

話不多說直接擼代碼

import random  
import scrapy
import logging
class proxMiddleware(object):
#proxy_list=[{'http': 'http://123.157.146.116:8123'}, {'http': 'http://116.55.16.233:8998'}, {'http': 'http://115.85.233.94:80'}, {'http': 'http://180.76.154.5:8888'}, {'http': 'http://139.213.135.81:80'}, {'http': 'http://124.88.67.14:80'}, {'http': 'http://106.46.136.90:808'}, {'http': 'http://106.46.136.226:808'}, {'http': 'http://124.88.67.21:843'}, {'http': 'http://113.245.84.253:8118'}, {'http': 'http://124.88.67.10:80'}, {'http': 'http://171.38.141.12:8123'}, {'http': 'http://124.88.67.52:843'}, {'http': 'http://106.46.136.237:808'}, {'http': 'http://106.46.136.105:808'}, {'http': 'http://106.46.136.190:808'}, {'http': 'http://106.46.136.186:808'}, {'http': 'http://101.81.120.58:8118'}, {'http': 'http://106.46.136.250:808'}, {'http': 'http://106.46.136.8:808'}, {'http': 'http://111.78.188.157:8998'}, {'http': 'http://106.46.136.139:808'}, {'http': 'http://101.53.101.172:9999'}, {'http': 'http://27.159.125.68:8118'}, {'http': 'http://183.32.88.133:808'}, {'http': 'http://171.38.37.193:8123'}]
proxy_list=[
    "http://180.76.154.5:8888",
    "http://14.109.107.1:8998",
    "http://106.46.136.159:808",
    "http://175.155.24.107:808",
    "http://124.88.67.10:80",
    "http://124.88.67.14:80",
    "http://58.23.122.79:8118",
    "http://123.157.146.116:8123",
    "http://124.88.67.21:843",
    "http://106.46.136.226:808",
    "http://101.81.120.58:8118",
    "http://180.175.145.148:808"

]
def process_request(self,request,spider):
    # if not request.meta['proxies']:
    ip = random.choice(self.proxy_list)
    print ip
    #print 'ip=' %ip
    request.meta['proxy'] = ip

主要的原理:

給出一個代理列表,然后在這個列表中隨機取出一個代理,設置在request中,其中request.meta['proxy']就是設置代理的格式

但是現在主要的問題就是沒有代理ip可用,如果去買的話又太貴了,自己玩玩買代理不值當,所以只好自己寫爬蟲去爬取免費的代理了,但是免費的代理存活的時間是有限的,這是個非常麻煩的事情,我提供的方法就是實現自己的一個ip代理池,每天定時更新自己的代理池,具體的實現方法會在下一篇文章中介紹,現在提供一段代碼用來爬
取西刺網站的代理

直接擼代碼,接招吧

#coding:utf-8
import requests
from bs4 import BeautifulSoup
import threading
import Queue
class Get_ips():
def __init__(self,page):
    self.ips=[]
    self.urls=[]
    for i in range(page):
        self.urls.append("http://www.xicidaili.com/nn/" + str(i))
    self.header = {"User-Agent": 'Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0'}
    #self.file=open("ips",'w')
    self.q=Queue.Queue()
    self.Lock=threading.Lock()
def get_ips(self):
    for url in self.urls:
        res = requests.get(url, headers=self.header)
        soup = BeautifulSoup(res.text, 'lxml')
        ips = soup.find_all('tr')
        for i in range(1, len(ips)):
            ip = ips[i]
            tds = ip.find_all("td")
            ip_temp = "http://" + tds[1].contents[0] + ":" + tds[2].contents[0]
            # print str(ip_temp)
            self.q.put(str(ip_temp))

def review_ips(self):
    while not self.q.empty():
        ip=self.q.get()
        try:
            proxy={"http": ip}
            #print proxy
            res = requests.get("http://www.baidu.com", proxies=proxy,timeout=5)
            self.Lock.acquire()
            if res.status_code == 200:
                self.ips.append(ip)
                print ip
                self.Lock.release()
        except Exception:
            pass
            #print 'error'
def main(self):
    self.get_ips()
    threads=[]
    for i in range(40):
        threads.append(threading.Thread(target=self.review_ips,args=[]))
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    return self.ips
def get_ip():
my=Get_ips(4)
return my.main()
get_ip()

實現的原理

這里用到了BeautifulSoup解析頁面,然后將提取到的代理交給隊列,然后再通過共享隊列分配給線程,這里主要開啟線程通過設置代理ip訪問一個網站,因為訪問網站的時間比較長,因此要開起多個線程,相信大家能夠學習設置代理ip了應該都是比較上手的了,這里具體的代碼就不一一解釋了,如果代碼有什么問題可以及時聯系我,我的聯系方式在關於我的一欄中有提到

補充

想要ip應用起來,還要在配置文件settings中添加DOWNLOADER_MIDDLEWARES = { 'demo.proxy.proxMiddleware':400 }這里的demo是工程的名字,proxy是py文件的名,proxMiddleware是類的名字

當然這里可能你覺得proxy_list寫在這里有點冗余,你可以在配置文件中定義,然后將配置文件的內容import到py文件中

以上全是博主慢慢摸索出來的,可以說自學一門技術真的很難,學習python爬蟲已經有兩三個月了,可以說全是自己通過看項目,網上查資料才有了今天的成功,不過現在還有幾個問題沒有解決,就是分布式爬蟲、移動端爬取,博主接下來就要主攻這兩個方面,學好之后會在自己的博客上分享學習心得的,因為網上沒有系統的學習教程,對於自學的人來說實在是太痛苦了


免責聲明!

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



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