python - Scrapy返回多个项目

标签 python web-scraping scrapy scrapy-spider

我是新来的Scrapy,我真的只是失去了我如何能在一个块中返回多个项目。

基本上,我得到了一个HTML标签,该标签的引号包含嵌套的文本标签,作者姓名以及一些有关该引号的标签。

此处的代码仅返回一个引号,仅此而已。它不使用循环返回其余部分。我已经在网上搜索了好几个小时,但无可救药。到目前为止,这是我的代码:

Spider.py

import scrapy
from scrapy.loader import ItemLoader
from first_spider.items import FirstSpiderItem

class QuotesSpider(scrapy.Spider):
name = 'quotes'
allowed_domains = ['quotes.toscrape.com']
start_urls = ['http://quotes.toscrape.com/']

def parse(self, response):
    l = ItemLoader(item = FirstSpiderItem(), response=response)

    quotes = response.xpath("//*[@class='quote']")

    for quote in quotes:
        text = quote.xpath(".//span[@class='text']/text()").extract_first()
        author = quote.xpath(".//small[@class='author']/text()").extract_first()
        tags = quote.xpath(".//meta[@class='keywords']/@content").extract_first()

        # removes quotation marks from the text
        for c in ['“', '”']:
            if c in text:
                text = text.replace(c, "")

        l.add_value('text', text)
        l.add_value('author', author)
        l.add_value('tags', tags)
        return l.load_item()

    next_page_path = 
    response.xpath(".//li[@class='next']/a/@href").extract_first()

    next_page_url = response.urljoin(next_page_path)
    yield scrapy.Request(next_page_url)

Items.py
import scrapy

class FirstSpiderItem(scrapy.Item):

text = scrapy.Field()
author = scrapy.Field()
tags = scrapy.Field()

这是我要抓取的页面:

Link

最佳答案

我也在寻找相同问题的解决方案。这是我找到的解决方案:

def parse(self, response):
    for selector in response.xpath("//*[@class='quote']"):
        l = ItemLoader(item=FirstSpiderItem(), selector=selector)
        l.add_xpath('text', './/span[@class="text"]/text()')
        l.add_xpath('author', '//small[@class="author"]/text()')
        l.add_xpath('tags', './/meta[@class="keywords"]/@content')
        yield l.load_item()

    next_page = response.xpath(".//li[@class='next']/a/@href").extract_first()
    if next_page is not None:
        yield response.follow(next_page, callback=self.parse)

要从文本中删除引号,可以在 items.py 中使用输出处理器。
from scrapy.loader.processors import MapCompose

def replace_quotes(text):
    for c in ['“', '”']:
        if c in text:
            text = text.replace(c, "")
    return text

class FirstSpiderItem(scrapy.Item):
    text = scrapy.Field()
    author = scrapy.Field()
    tags = scrapy.Field(output_processor=MapCompose(replace_quotes))

请让我知道它是否有帮助。

关于python - Scrapy返回多个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46571543/

相关文章:

python - 从 slack url 下载加密/压缩的 7z 文件

python - 当url变化为50的倍数时如何抓取页面?

css - 使用 rvest 抓取网站数据

python-3.x - 使用规则在主页面完成后抓取 'next' 页面

python - 在Python中将数组转换为元组/列表的快速方法?

python - Scapy:向 fields_desc 添加更多字段

python - 如何修复安装 Jupyter Notebook 时发生的错误?

python - 如何获取每个标签的数据?

python - Scrapy蜘蛛不保存html文件

python - 用字符串 "None"替换 Scrapy.css 返回的空/空白数据