Scrapy抓取西刺高匿代理ip

来源:互联网 发布:找出出现最多的词 算法 编辑:程序博客网 时间:2024/06/06 15:04

如题:因为想试试代理ip,所以就想着在西刺上爬一些ip用用

如上两节所示,具体如何建立Scrapy工程的细节不在赘述。

scrapy startproject xiciscrapy 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.htmlimport scrapyclass XiciItem(scrapy.Item):    # define the fields for your item here like:    # name = scrapy.Field()    passclass 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-8import scrapyfrom scrapy.spiders import CrawlSpider, Rulefrom scrapy.linkextractors import LinkExtractorfrom xici.items import ipItemclass 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.htmlclass 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 时添加用户代理。