1. 程式人生 > >Scrapy抓取西刺高匿代理ip

Scrapy抓取西刺高匿代理ip

如題:因為想試試代理ip,所以就想著在西刺上爬一些ip用用

如上兩節所示,具體如何建立Scrapy工程的細節不在贅述。

scrapy startproject xici

scrapy genspider xici http://www.xicidaili.com/nn/

建立工程後,使用IDE開啟,首先編輯item

#items.py
# -*- coding: utf-8 -*-

# Define here the models for your scraped items
#
# See documentation in:
# http://doc.scrapy.org/en/latest/topics/items.html
import scrapy class XiciItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() pass class ipItem(scrapy.Item): ip = scrapy.Field() port = scrapy.Field() address = scrapy.Field() type = scrapy.Field() protocol = scrapy.Field() speed = scrapy.Field
() time = scrapy.Field() alive = scrapy.Field() proof = scrapy.Field()

然後編寫spider,在資料夾spiders下建立spider.py。

# coding=utf-8
import scrapy
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from xici.items import ipItem

class Spider(CrawlSpider):
name = 'xici' allowed_domains = ['www.xicidaili.com'] start_urls = ['http://www.xicidaili.com/nn/'] rules = [ Rule(LinkExtractor(allow=(r"http://www.xicidaili.com/nn/d+")),callback="parse_item") ] def parse_item(self,response): ipItems = response.css('#ip_list tr:not(:first-child)') for item in ipItems: ip = ipItem() ip["ip"] = item.css("td:nth-child(2)::text").extract() ip["port"] = item.css("td:nth-child(3)::text").extract() ip["address"] = item.css("td:nth-child(4) a::text").extract() ip["type"] = item.css("td:nth-child(5)::text").extract() ip["protocol"] = item.css("td:nth-child(6)::text").extract() ip["speed"] = item.css("td:nth-child(7) div::attr(title)").extract() ip["time"] = item.css("td:nth-child(8) div::attr(title)").extract() ip["alive"] = item.css("td:nth-child(9)::text").extract() ip["proof"] = item.css("td:nth-child(10)::text").extract() yield ip

在這個過程中遇到了一個問題,即簡單的爬取西刺頁面是無法爬取的,會遇到503錯誤。原因是需要設定user-agent。

當然,你想指導到底它設定了什麼樣的限制,你可以訪問robot.txt檢視詳情

http://www.xicidaili.com/robots.txt

robot.txt檔案包含了該網站允許的使用者代理和允許爬取的網頁。

如何設定User-agent

在工程目錄下找到Settings.py,然後找到其中的USER-AGENT一行,將註釋去掉。可以將其設定為

USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36'

這樣,Scrapy就可以訪問西刺了
假設此時,我們需要使用scrapy shell來檢查是否可以訪問西刺網站,並且除錯程式,我們發現像原來那樣使用

scrapy shell "http://www.xicidaili.com/nn"

並不能成功訪問。那麼我們需要在scrapy shell 上也設定user-agent,具體設定如下

scrapy shell -s USER_AGENT="Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.90 Safari/537.36" "http://www.xicidaili.com/nn/"

所以OK,這樣我們就可以成功的訪問西刺了。此時可以使用view(response)來檢視爬取下來的網頁是否符合要求。

最後,處理Item,儲存到本地。

# -*- coding: utf-8 -*-
import json
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html


class XiciPipeline(object):
    def __init__(self):
        self.file = open('result.jl', 'w', encoding='utf-8')

    def process_item(self, item, spider):
        line = json.dumps(dict(item), ensure_ascii=False) + '\n'
        self.file.write(line)
        return item

此時,記得在Settings.py中啟用pipeLine。

這裡收穫最大的是學習到了如何給Scarpy新增使用者代理和在使用Scrapy shell 時新增使用者代理。