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),

    )












猜你喜欢

转载自blog.csdn.net/slbwgslz/article/details/80493313
今日推荐