scrapy 爬取百度知道,多spider子一个项目中,使用一个pielines

简介: 爬取过程中 遇见 百度蜘蛛反爬 robot.txt,我们可以在scrapy 的setting.py 配置文件下配置 ROBOTSTXT_OBEY = False 最终代码 # -*- coding: utf-8 -*-from scrapy.spider import Spiderfrom scrapy.contrib.spiders import CrawlSpi

爬取过程中 遇见 百度蜘蛛反爬 robot.txt,我们可以在scrapy 的setting.py 配置文件下配置

ROBOTSTXT_OBEY = False



最终代码

# -*- coding: utf-8 -*-
from scrapy.spider import Spider
from scrapy.contrib.spiders import CrawlSpider, Rule
#from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.linkextractors import LinkExtractor
from scrapy.selector import Selector
from scrapy.http import Request, HtmlResponse
from scrapy import log

from items import BDzdItem


class BDzdSpider(CrawlSpider):
    global qa_number;
    qa_number=0;
    """爬取百度知道 银行"""
    log.msg("log",level=log.DEBUG)
    def _requests_to_follow(self, response):
        if not isinstance(response, HtmlResponse):
            return
        seen = set()
        for n, rule in enumerate(self._rules):
            links = [lnk for lnk in rule.link_extractor.extract_links(response)
                     if lnk not in seen]
            if links and rule.process_links:
                links = rule.process_links(links)
            for link in links:
                if link.text.find("银行") == -1:
                    continue;
                seen.add(link)
                r = Request(url=link.url, callback=self._response_downloaded)
                r.meta.update(rule=n, link_text=link.text)
                yield rule.process_request(r)

    name = "bankSpider"


    download_delay = 1
    allowed_domains = ["zhidao.baidu.com"]
    start_urls = [
        "https://zhidao.baidu.com/question/1796062605517856547.html?fr=iks&word=%D2%F8%D0%D0&ie=gbk"
    ]

    rules = [
        Rule(LinkExtractor(allow=('/question/.*'),
                               restrict_xpaths=('//a[@class="related-link"]')),
             callback='parse_item',
             follow=True)
    ]

    def parse_item(self, response):
        #return;
       # open("aa.txt", 'wb').write(response.body)
        sel = Selector(response)
        url=response._url;
        question=sel.xpath('//span[@class="ask-title "]/text()').extract()
        answer = sel.xpath('//pre[@class="best-text mb-10"]/text()').extract()
        otherAnswer=sel.xpath('//div[@class="answer-text line"]/span/text()').extract()
        #sites=sel.xpath('//a[@class="related-link"]')

        item = BDzdItem()
        item["question"] = ''.join(question);
        if len(answer) > 0:
            item["answer"] = ''.join(answer);#因为xpath text()截出来可能是字符数组,要转成字符
        elif len(otherAnswer) > 0:
            item["answer"] = ''.join(otherAnswer[0]);
        else:
            return;

        global qa_number
        qa_number=qa_number+1;
        item["number"]=qa_number
        print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ 第" + str(qa_number)+" 条";
        print "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@" + url;
        print "##########################################" + item["question"];
        print "*******************************************" +  item["answer"];

        yield item

如果有多个spider在一个项目中,可以在pipelines.py中这样写

# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import json
import codecs

class TutorialPipeline(object):
    def process_item(self, item, spider):
        print "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%0"
        return item


class BDzdPipeline(object):
    def __init__(self):
        self.bankFile = codecs.open('data_bank.json', 'wb', encoding='utf-8')#银行
        self.mobileFile = codecs.open('data_mobile.json', 'wb', encoding='utf-8')#移动
        self.baoxianFile = codecs.open('data_baoxian.json', 'wb', encoding='utf-8')#保险
        self.jinrongFile = codecs.open('data_jinrong.json', 'wb', encoding='utf-8')#金融

    def process_item(self, item, spider):
        line = json.dumps(dict(item)) + '\n'
        if spider.name=='bankSpider':
            self.bankFile.write(line.decode("unicode_escape"))
        elif spider.name == 'mobileSpider':
            self.mobileFile.write(line.decode("unicode_escape"))
        elif spider.name == 'baoxianSpider':
            self.baoxianFile.write(line.decode("unicode_escape"))
        elif spider.name == 'jinrongSpider':
            self.jinrongFile.write(line.decode("unicode_escape"))
        return item



目录
相关文章
|
10月前
|
数据采集 中间件 Python
Scrapy爬虫:利用代理服务器爬取热门网站数据
Scrapy爬虫:利用代理服务器爬取热门网站数据
|
9月前
|
数据采集 数据库 Python
为什么基于 Django 和 Scrapy 的项目需要 @sync_to_async 装饰器
通过使用 @sync_to_async 装饰器,我们可以在 Scrapy 的异步环境中高效地调用同步的 Django ORM 操作。这样可以避免阻塞事件循环,充分利用 Scrapy 的异步 I/O 优势,从而提升爬虫的性能和并发处理能力。在构建基于 Django 和 Scrapy 的项目时,理解并正确使用 @sync_to_async 是非常重要的,这将帮助你构建高效、健壮的应用程序。
|
8月前
|
数据采集 存储 缓存
使用Scrapy进行网络爬取时的缓存策略与User-Agent管理
使用Scrapy进行网络爬取时的缓存策略与User-Agent管理
|
9月前
|
Web App开发 iOS开发 Python
经验大分享:scrapy框架爬取糗妹妹网站qiumeimei.com图片
经验大分享:scrapy框架爬取糗妹妹网站qiumeimei.com图片
55 0
|
10月前
|
数据采集 前端开发 中间件
python-scrapy框架(一)Spider文件夹的用法讲解
python-scrapy框架(一)Spider文件夹的用法讲解
222 0
|
XML 数据采集 JSON
scrapy_selenium爬取Ajax、JSON、XML网页:豆瓣电影
在网络爬虫的开发过程中,我们经常会遇到一些动态加载的网页,它们的数据不是直接嵌入在HTML中,而是通过Ajax、JSON、XML等方式异步获取的。这些网页对于传统的scrapy爬虫来说,是很难直接解析的。那么,我们该如何使用scrapy_selenium来爬取这些数据格式的网页呢?本文将为你介绍scrapy_selenium的基本原理和使用方法,并给出一个实际的案例。
146 0
|
10月前
|
数据采集 JavaScript 开发者
使用Scrapy有效爬取某书广告详细过程
使用Scrapy有效爬取某书广告详细过程
使用Scrapy有效爬取某书广告详细过程
|
10月前
|
数据采集 Web App开发 搜索推荐
项目配置之道:优化Scrapy参数提升爬虫效率
项目配置之道:优化Scrapy参数提升爬虫效率
|
数据采集 存储 JSON
「Python」爬虫-9.Scrapy框架的初识-公交信息爬取
本文将讲解如何使用scrapy框架完成北京公交信息的获取。
789 0
|
10月前
|
数据采集 Python
Scrapy框架 -- 深度爬取并持久化保存图片
Scrapy框架 -- 深度爬取并持久化保存图片
174 0