scrapy使用CrawlSpider方式爬取百度贴吧帖子跟图片

今天用CrawlSpider方式爬取百度贴吧,不得不说,这种方法太牛逼了,只用了不到二十行的代码
  • 创建项目 scrapy startproject 项目名
  • 进入项目然后生成爬虫 scrapy genspider -t crawl 爬虫 爬取范围

主要代码

# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule


class BslnSpider(CrawlSpider):
    name = 'bsln'
    allowed_domains = ['baidu.com']
    start_urls = ['https://tieba.baidu.com/f?kw=%E5%B7%B4%E5%A1%9E%E7%BD%97%E9%82%A3']

    rules = (
        #这是帖子详情页的url
        Rule(LinkExtractor(allow=r'/p/\d+'), callback='parse_item'),
        #这是下一页的
        Rule(LinkExtractor(allow=r'https://tieba.baidu.com/f\?kw=%E5%B7%B4%E5%A1%9E%E7%BD%97%E9%82%A3&ie=utf-8&pn=\d+'), follow=True),
    )

    def parse_item(self, response):
        """处理帖子详情页"""
        item = {}
        item["标题"] = response.xpath('//div[@class="left_section"]//h3/text()').extract_first()
        item["图片"] = response.xpath('//img[@class="BDE_Image"]/@src').extract_first()
        yield item

pipelines.py中保存数据到mongodb

# -*- coding: utf-8 -*-
from pymongo import MongoClient


#链接数据库
client = MongoClient(host="127.0.0.1", port=27017)
#创建数据库
db = client.BSLN_tieba

class TbPipeline:
    def process_item(self, item, spider):
        """保存数据到mongo"""
        #插入数据
        db.data.insert_one(dict(item))
        #print(item)

settings.py中主要弄几点

#通过在用户代理上标识自己,负责任地爬行
USER_AGENT = 'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)'
#默认遵守robots.txt,请求前会先请求这个,弄成False就不会请求了
ROBOTSTXT_OBEY = False
#最大并发(默认16)
CONCURRENT_REQUESTS = 64
#禁用cookies(默认启用)
COOKIES_ENABLED = False
#开启管道(开启才能用piplines.py)
ITEM_PIPELINES = {
    'tb.pipelines.TbPipeline': 300,
}

运行截图,本次提取了每个帖子的标题及图片的地址,没有的话scrapy会自动设置为None

运行截图
在这里插入图片描述
数据库截图
在这里插入图片描述

使用CrawlSpider适合url地址比较有规律的,它使用正则匹配所有url,然后自动请求,省了人工自己找的时间

就是下面这个了

 rules = (
        #这是帖子详情页的url
        Rule(LinkExtractor(allow=r'/p/\d+'), callback='parse_item'),
        #这是下一页的
        Rule(LinkExtractor(allow=r'https://tieba.baidu.com/f\?kw=%E5%B7%B4%E5%A1%9E%E7%BD%97%E9%82%A3&ie=utf-8&pn=\d+'), follow=True),
    )
要反反爬的话还要在(middlewares.py)下载中间件中的设置随机的请求头跟随机代理ip
    def process_request(self, request, spider):
		"""这个方法可以在请求之前设置UA跟代理ip"""
        return None

还有很多不足的地方,就这样

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值