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

爬取过程中 遇见 百度蜘蛛反爬 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
时间: 2024-08-01 19:25:25

scrapy 爬取百度知道,多spider子一个项目中,使用一个pielines的相关文章

教你分分钟学会用python爬虫框架Scrapy爬取心目中的女神

来源:http://www.cnblogs.com/wanghzh/p/5824181.html 本博文将带领你从入门到精通爬虫框架Scrapy,最终具备爬取任何网页的数据的能力.本文以校花网为例进行爬取,校花网:http://www.xiaohuar.com/,让你体验爬取校花的成就感.   Scrapy,Python开发的一个快速,高层次的屏幕抓取和web抓取框架,用于抓取web站点并从页面中提取结构化的数据.Scrapy用途广泛,可以用于数据挖掘.监测和自动化测试. Scrapy吸引人的地

Python爬虫爬取百度贴吧多线程版

XPath提取内容 //定位根节点 / 往下层寻找 提取文本内容:/text() 提取属性内容 : /@XXXX 常规匹配 #-*-coding:utf8-*- from lxml import etree html = ''' <!DOCTYPE html> <html> <head lang="en">     <meta charset="UTF-8">     <title>测试-常规用法</

教你用python3根据关键词爬取百度百科的内容_python

前言 关于python版本,我一开始看很多资料说python2比较好,因为很多库还不支持3,但是使用到现在为止觉得还是pythin3比较好用,因为编码什么的问题,觉得2还是没有3方便.而且在网上找到的2中的一些资料稍微改一下也还是可以用. 好了,开始说爬百度百科的事. 这里设定的需求是爬取北京地区n个景点的全部信息,n个景点的名称是在文件中给出的.没有用到api,只是单纯的爬网页信息.  1.根据关键字获取url 由于只需要爬取信息,而且不涉及交互,可以使用简单的方法而不需要模拟浏览器. 可以直

代码初步写好后,可能我们想达到的效果是:往集合lists的子集合tempList中添加一个元素6,而原有的集合保持不变。

问题描述 List<Object> lists = new ArrayList<Object>(); lists.add("1"); lists.add("2"); lists.add("3"); lists.add("4"); List<Object> tempList = lists.subList(2, lists.size()); tempList.add("6"

Python使用Scrapy爬取妹子图

前面我们给大家介绍了使用nodejs来爬取妹纸图片的方法,下面我们来看下使用Python是如何实现的呢,有需要的小伙伴参考下吧. Python Scrapy爬虫,听说妹子图挺火,我整站爬取了,上周一共搞了大概8000多张图片.和大家分享一下. 核心爬虫代码 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 # -*- coding: utf-8

scrapy 爬取 useragent

useragentstring.com 网站几乎廊括了所有的User-Agent,刚学了scrapy,打算那它练手,把上面的 user-agent 爬取下来. 本文只爬取常见的 FireFox, Chrome, Opera, Safri, Internet Explorer 一.创建爬虫项目 1.创建爬虫项目useragent $ scrapy startproject useragent 2.进入项目目录 $ cd useragent 3.生成爬虫文件 ua 这一步不是必须的,不过有了就方便些

使用Scrapy爬取知乎网站

本文主要记录使用使用 Scrapy 登录并爬取知乎网站的思路.Scrapy的相关介绍请参考 使用Scrapy抓取数据. 相关代码,见 https://github.com/javachen/scrapy-zhihu-github ,在阅读这部分代码之前,请先了解 Scrapy 的一些基本用法. 使用cookie模拟登陆 关于 cookie 的介绍和如何使用 python 实现模拟登陆,请参考python爬虫实践之模拟登录. 从这篇文章你可以学习到如何获取一个网站的 cookie 信息.下面所讲述

scrapy 爬取自己的博客

定义项目 # -*- coding: utf-8 -*- # items.py import scrapy class LianxiCnblogsItem(scrapy.Item): # define the fields for your item here like: # name = scrapy.Field() url = scrapy.Field() title = scrapy.Field() article = scrapy.Field() post_date = scrapy.F

java网络爬虫爬取百度新闻

采用commons-httpclient commons-httpclient是一个遗留版本,现在官方已经不推荐使用了. lucene采用4.3版本 所需jar包 package com.lulei.util; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream;