scrapy 相关函数

本文档介绍如何使用Scrapy框架爬取http://quotes.toscrape.com/上的信息。主要内容包括:定义items.py中的数据结构,利用CSS选择器提取HTML内容,获取标签文本和属性值,进行URL拼接,递归调用,文件保存,配置pipelines进行数据处理,以及将数据存储到MongoDB中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

catalog

参考爬取网站http://quotes.toscrape.com/

  1. 返回爬取网站的html
response.text
  1. 在items.py中定义爬取内容的数据结构
class QuotesItem(scrapy.Item):
    # define the fields for your item here like:
    # name = scrapy.Field()
    text = scrapy.Field()
    author = scrapy.Field()
    tags = scrapy.Field()
  1. css选择器用法
quotes = response.css('.quote')
  1. 输出标签中的文本内容
text = quote.css('.quote::text')
  1. 取标签中的第一个值
author = quote.css('.author::text').extract_first()
  1. 取标签中的所有值
tags = quote.css('.tags .tag::text').extract()
  1. 网站调试
scrapy shell quotes.toscrape.com
  1. 爬取内容的存储,item的定义
 item = QuotesItem()#define the item as you define in items.py
            text = quote.css('.text::text').extract_first()#select text tag which in this quote tag and then output the text content
            author = quote.css('.author::text').extract_first()
            tags = quote.css('.tags .tag::text').extract()
            item['text'] = text
            item['author'] = author
            item['tags'] = tags
  1. 提取tag中的属性的值
next = response.css('.pager .next a::attr(href)').extract_first()#get the url of next page
  1. url拼接
url = response.urljoin(next)#quotes.toscrape.com + next
  1. 递归调用自己
yield  scrapy.Request(url = url, callback = self.parse())
  1. 文件保存
scrapy crawl quotetutorial -o quotes.jl
scrapy crawl quotetutorial -o quotes.json
scrapy crawl quotetutorial -o quotes.csv
```python
scrapy crawl quotetutorial -o quotes.xml
scrapy crawl quotetutorial -o quotes.marshal
scrapy crawl quotetutorial -o quotes.pickle
  1. pipelines

对item进行处理

class QuotesPipeline:
    def _init_(self):
        self.limit = 50

    def process_item(self, item, spider):
        if item['text']:
            if len(item['text'])>self.limit:
                item['text'] = item['text'][0:self.limit].rstrip() + '...'
            return item
        else:
            return DropItem('Missing Text')

保存到MongoDB中

class MongoPipeline(object):
    def __init__(self,mongo_url,mongo_db):
        self.mongo_url = mongo_url
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls,crawler):
        return cls(
            mongo_url = crawler.settings.get('MONGO_URL'),
            mongo_db = crawler.settings.get('MONGO_DB')
        )

    def open_spider(self,spider):
        self.client = pymongo.MongoClient(self.mongo_url)
        self.db = self.client[self.mongo_db]

    def process_item(self,item,spider):
        name = item.__class__.__name__
        self.db[name].insert(dict(item))
        return item
    def close_spider(self,spider):
        self.client.close()

在settings.py中配置一下MongoDB和PipeLine

MONGO_URL = 'localhost'
MONGO_DB = 'quotesdb'
ITEM_PIPELINES = {
   'quotes.pipelines.QuotesPipeline': 300,
   'quotes.pipelines.MongoPipeline': 400,
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值