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