鱼C论坛

 找回密码
 立即注册
查看: 3075|回复: 1

关于scrapy中的CrawlSpider,如何添加headers?

[复制链接]
发表于 2017-8-16 13:13:54 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 syxuming 于 2017-8-16 13:15 编辑

网上看到CrawSpider的例子如下
  1. import scrapy
  2. from scrapy.spiders import CrawlSpider, Rule
  3. from scrapy.linkextractors import LinkExtractor

  4. class MySpider(CrawlSpider):
  5.     name = 'example.com'
  6.     allowed_domains = ['example.com']
  7.     start_urls = ['http://www.example.com']

  8.     rules = (
  9.         Rule(LinkExtractor(allow=('category\.php', ), deny=('subsection\.php', ))),
  10.         Rule(LinkExtractor(allow=('item\.php', )), callback='parse_item'),
  11.     )

  12.     def parse_item(self, response):
  13.         self.logger.info('Hi, this is an item page! %s', response.url)
  14.         item = scrapy.Item()
  15.         item['name'] = response.xpath('//td[@id="item_name"]/text()').extract()
  16.         item['description'] = response.xpath('//td[@id="item_description"]/text()').extract()
  17.         return item
复制代码


但是有些网站需要添加headers才能正常访问,那么CrawlSpider中如何去添加header呢
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2017-8-16 15:24:28 | 显示全部楼层
参考:
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. from scrapy.contrib.spiders import CrawlSpider, Rule
  4. from scrapy.selector import Selector
  5. from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
  6. from scrapy.http import Request, FormRequest
  7. from zhihu.items import ZhihuItem



  8. class ZhihuSipder(CrawlSpider) :
  9.     name = "zhihu"
  10.     allowed_domains = ["www.zhihu.com"]
  11.     start_urls = [
  12.         "http://www.zhihu.com"
  13.     ]
  14.     rules = (
  15.         Rule(SgmlLinkExtractor(allow = ('/question/\d+#.*?', )), callback = 'parse_page', follow = True),
  16.         Rule(SgmlLinkExtractor(allow = ('/question/\d+', )), callback = 'parse_page', follow = True),
  17.     )
  18.     headers = {
  19.     "Accept": "*/*",
  20.     "Accept-Encoding": "gzip,deflate",
  21.     "Accept-Language": "en-US,en;q=0.8,zh-TW;q=0.6,zh;q=0.4",
  22.     "Connection": "keep-alive",
  23.     "Content-Type":" application/x-www-form-urlencoded; charset=UTF-8",
  24.     "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.111 Safari/537.36",
  25.     "Referer": "http://www.zhihu.com/"
  26.     }

  27.     #重写了爬虫类的方法, 实现了自定义请求, 运行成功后会调用callback回调函数
  28.     def start_requests(self):
  29.         return [Request("https://www.zhihu.com/login", meta = {'cookiejar' : 1}, callback = self.post_login)]

  30.     #FormRequeset出问题了
  31.     def post_login(self, response):
  32.         print 'Preparing login'
  33.         #下面这句话用于抓取请求网页后返回网页中的_xsrf字段的文字, 用于成功提交表单
  34.         xsrf = Selector(response).xpath('//input[@name="_xsrf"]/@value').extract()[0]
  35.         print xsrf
  36.         #FormRequeset.from_response是Scrapy提供的一个函数, 用于post表单
  37.         #登陆成功后, 会调用after_login回调函数
  38.         return [FormRequest.from_response(response,   #"http://www.zhihu.com/login",
  39.                             meta = {'cookiejar' : response.meta['cookiejar']},
  40.                             headers = self.headers,  #注意此处的headers
  41.                             formdata = {
  42.                             '_xsrf': xsrf,
  43.                             'email': '1095511864@qq.com',
  44.                             'password': '123456'
  45.                             },
  46.                             callback = self.after_login,
  47.                             dont_filter = True
  48.                             )]

  49.     def after_login(self, response) :
  50.         for url in self.start_urls :
  51.             yield self.make_requests_from_url(url)

  52.     def parse_page(self, response):
  53.         problem = Selector(response)
  54.         item = ZhihuItem()
  55.         item['url'] = response.url
  56.         item['name'] = problem.xpath('//span[@class="name"]/text()').extract()
  57.         print item['name']
  58.         item['title'] = problem.xpath('//h2[@class="zm-item-title zm-editable-content"]/text()').extract()
  59.         item['description'] = problem.xpath('//div[@class="zm-editable-content"]/text()').extract()
  60.         item['answer']= problem.xpath('//div[@class=" zm-editable-content clearfix"]/text()').extract()
  61.         return item

复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-4 09:30

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表