Python进阶之CrawlSpider的应用及Scrapy配置项的引用

1. CrawlSpider的应用

  • CrawlSpider可以根据规则自动分析链接的数据并按照正则的要求取出需要的数据

scrajpy startproject yg
cd yg

  • 注意-t crawl参数

scrapy genspider -t crawl 爬虫名称 域名

csun.py

  • 需求:爬取阳光问政的详情页内容
    • LinkExtractor 链接提取器
    • callback 回调函数
    • follow 继续提取下一页的url
    • allow里边写的是正则表达式
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule

class CsunSpider(CrawlSpider):
    name = 'csun'
    allowed_domains = ['sun0769.com']
    start_urls = ['http://wz.sun0769.com/political/index/politicsNewest?id=1']
    rules = (
        Rule(LinkExtractor(allow=r'wz.sun0769.com/political/index/politicsNewest\?id=\d+'),follow=True),
        Rule(LinkExtractor(
            allow=r'wz.sun0769.com/political/politics/index\?id=\d+'), callback='parse_item',follow=True),
    )

    def parse_item(self, response):
        item = {}
        #item['domain_id'] = response.xpath('//input[@id="sid"]/@value').get()
        #item['name'] = response.xpath('//div[@id="name"]').get()
        #item['description'] = response.xpath('//div[@id="description"]').get()
        item['content'] = response.xpath('//div[@class="details-box"]/pre/text()').extract_first()
        print(item)
        return item
  • 注意事项:
    • 数据要首先在url中,使用CrawlSpider会比较简单
    • 要对连接中的特殊字符如?前加\进行处理
    • 正则不需要写url的协议名例如http://等等
    • 列表页不需要callback,但需要follow
    • 详情页需要callback,但不需要follow

2. Scrapy配置项的引用

  • 在settings中添加的的配置项,需要以大写的形式书写
  • MY_HOST = ‘127.0.0.2’

  • 引用方式有两种,首先在items里对字段名进行设置
  • item[‘host’] = scrapy.fileld()

  • 在spider文件中引用:
    • 方法一:
    • from settings import MY_HOST

    • item[‘host’] = MY_HOST

    • 方法二:
    • item[‘host’] = self.settings.get(‘MY_HOST’)

  • 在pipeline里边引用
    • item[‘host’] = spider.settings.get(‘MY_HOST’)

评论 8
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

kingx3

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值