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



目录
相关文章
|
4月前
|
数据采集 XML 存储
构建一个简单的电影信息爬虫项目:使用Scrapy从豆瓣电影网站爬取数据
这个案例展示了如何使用 Scrapy 框架构建一个简单的爬虫项目,从网页中提取数据并保存到文件中。通过配置、编写爬虫代码、定义数据模型和数据处理管道,你可以灵活地构建各种爬虫应用。
105 0
构建一个简单的电影信息爬虫项目:使用Scrapy从豆瓣电影网站爬取数据
|
6月前
|
数据采集 开发者 Python
如何使用Scrapy框架爬取301跳转后的数据
如何使用Scrapy框架爬取301跳转后的数据
|
12月前
|
数据采集 Web App开发 存储
使用 Scrapy + Selenium 爬取动态渲染的页面
使用 Scrapy + Selenium 爬取动态渲染的页面
333 0
使用 Scrapy + Selenium 爬取动态渲染的页面
|
12月前
|
Python 容器
使用 Scrapy 框架来爬取数据
创建一个 Scrapy 项目,项目文件可以直接用 scrapy 命令生成,命令如下所示:scrapy startproject doubanmovie250 这个命令可以在任意文件夹运行。如果提示权限问题,可以加 sudo 运行该命令。
167 0
|
数据采集 数据库 Python
Scrapy爬取豆瓣
使用Scrapy爬取豆瓣Top250数据
|
数据采集 Python
Python爬虫:scrapy爬取腾讯社招职位信息
Python爬虫:scrapy爬取腾讯社招职位信息
156 0
|
数据采集 关系型数据库 MySQL
五十四、使用Scrapy爬取北京公交信息(将爬取的数据存入Mysql)
五十四、使用Scrapy爬取北京公交信息(将爬取的数据存入Mysql)
五十四、使用Scrapy爬取北京公交信息(将爬取的数据存入Mysql)
|
数据采集 XML 存储
【新闻推荐系统】(task3)Scrapy基础及新闻爬取实战
一、Scrapy的简介与安装 python环境的安装: python 环境,使用minicon
453 0
【新闻推荐系统】(task3)Scrapy基础及新闻爬取实战
|
数据采集 存储 JSON
Scrapy爬取makepolo网站数据深入详解
题记 之前对爬虫只是概念了解多,实战少。知道网上流行的有号称免费的八爪鱼等(实际导出数据收费)。 大致知道,所有爬虫要实现爬取网页信息,需要定义正则匹配规则。
180 0
Scrapy爬取makepolo网站数据深入详解
|
数据挖掘 Python
Crawler之Scrapy:数据挖掘必备的scrapy框架之最完整爬取网页内容攻略
Crawler之Scrapy:数据挖掘必备的scrapy框架之最完整爬取网页内容攻略
Crawler之Scrapy:数据挖掘必备的scrapy框架之最完整爬取网页内容攻略