Python Scrapy 全站爬虫

基本命令:

scrapy startproject test2  创建工程

scrapy genspider test www.abc.com    创建基于scrapy.Spider 的爬虫  

scrapy genspider -t crawl test www.abc.com 创建基于CrawlSpider的爬虫

scrapy  crawl test -o test.json 运行爬虫test数据保存到test.json中


抓取百度应用商店信息代码如下:

import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class test(CrawlSpider):
    name = 'test'
    allowed_domains = ['as.baidu.com']
    start_urls = [
               'https://as.baidu.com/',
               ]

    rules = (
        Rule(LinkExtractor(allow='https://as.baidu.com/software/',deny='https://as.baidu.com/software/\d+\.html'),  follow=True),
            
        Rule(LinkExtractor(allow='https://as.baidu.com/software/\d+\.html'), callback='parse_item', follow=True),
    )

    def parse_item(self, response):
        i = {}
        i['url']=response.url
        return i

全站爬虫原理:

            1、先获取start_urls中网页内容A

            2、在获得的网页内容A中 匹配rules地址

            3、获取 匹配的rules地址 的页面内容B ,如果设置了callback 就调用回调函数,如果follow=True 就继续在页面内容B中匹配rules地址并重复步骤3



注意:

rules中存在多条匹配规则时 一个url满足其中一条就不会继续匹配吓一跳了。如上面例子

如果如下面写下法 就获取不到数据

    rules = (
        Rule(LinkExtractor(allow='https://as.baidu.com/software/'),  follow=True),
            
        Rule(LinkExtractor(allow='https://as.baidu.com/software/\d+\.html'), callback='parse_item', follow=True),
    )
但是换个位置就可以获取到数据了
    rules = (
      
        Rule(LinkExtractor(allow='https://as.baidu.com/software/',deny='https://as.baidu.com/software/\d+\.html'),  follow=True),
        Rule(LinkExtractor(allow='https://as.baidu.com/software/\d+\.html'), callback='parse_item', follow=True),

    )












  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值