2017-06-20 88 views
-1

我在我的項目中使用代理輪換,以防止被禁止從網站,我不得不刮到一個網址http://website/0001http://website/9999列表,當它檢測到我我正在刮他們把我送到網站/ contact.html。手動設置一個代理死亡使用scrapy旋轉代理包

我已經在設置
ROTATING_PROXY_LIST = [ 'proxy1.com:8000', 'proxy2.com:8031', # ... ]

我的代理列表,我創造了這個蜘蛛:

next_page_url = response.url[17:]//getting the relative url from website/page 

    if next_page_url == "contact.html": 

     absolute_next_page = response.urljoin(last_page) 
     yield Request(absolute_next_page) 
     //should try the same page with different proxy 
    else: 
     next_page_url = int(next_page_url)+1 
     last_page = str(next_page_url).zfill(4) 
     absolute_next_page = response.urljoin(last_page) 
     yield Request(absolute_next_page)` 

但它給出了一個錯誤說UnboundLocalError:分配之前引用局部變量「last_page」

我該如何指定代理在這個蜘蛛中死亡?還是有另一種方式來做同樣的事情?

回答

0

你想問什麼?

你是說你有錯誤

UnboundLocalError: local variable 'last_page' referenced before assignment 

您嘗試使用未初始化的貨幣變量此錯誤狀態。

因此,爲了防止這種錯誤,改變這樣

next_page_url = response.url[17:]//getting the relative url from website/page 

next_page_url = int(next_page_url)+1 
last_page = str(next_page_url).zfill(4) 
absolute_next_page = response.urljoin(last_page) 

if next_page_url == "contact.html": 

     next_page_url = int(next_page_url)+1 
     absolute_next_page = response.urljoin(last_page) 

     req = Request(url = absolute_next_page) 

     // If you want to try the same link again, then do this 
     // req = Request(url = response.url) 

     req.meta['proxy'] = random.choice(ROTATING_PROXY_LIST) // choose a random proxy 

     yield req 

else: 

     yield Request(absolute_next_page) 
+0

對不起你的代碼,忘了提,我已經初始化last_page作爲start_urls變量後,全局變量,因爲如果它在contact.html進入,它必須返回到我在上次請求中嘗試訪問的鏈接,但我仍然不知道如何執行此操作。 –

+0

告訴我你在pastebin.com上的完整代碼 – Umair

+0

這裏https://pastebin.com/xDcC2AH8 –