【问题标题】:Scrapy returns more results than expectedScrapy 返回的结果比预期的要多
【发布时间】:2016-11-13 21:09:12
【问题描述】:

这是问题的延续:Extract from dynamic JSON response with Scrapy

我有一个从 JSON 响应中提取值的 Scrapy 蜘蛛。它运行良好,提取了正确的值,但不知何故它进入了一个循环并返回比预期更多的结果(重复结果)。

例如,对于 test.txt 文件中提供的 17 个值,它返回 289 结果,这意味着 17 times more 超出预期。

蜘蛛内容如下:

import scrapy
import json
from whois.items import WhoisItem

class whoislistSpider(scrapy.Spider):
    name = "whois_list"
    start_urls = []
    f = open('test.txt', 'r')
    global lines
    lines = f.read().splitlines()
    f.close()
    def __init__(self):
        for line in lines:
            self.start_urls.append('http://www.example.com/api/domain/check/%s/com' % line)

    def parse(self, response):
        for line in lines:
            jsonresponse = json.loads(response.body_as_unicode())
            item = WhoisItem()
            domain_name = list(jsonresponse['domains'].keys())[0]
            item["avail"] = jsonresponse["domains"][domain_name]["avail"]
            item["domain"] = domain_name
            yield item

items.py 内容如下

import scrapy

class WhoisItem(scrapy.Item):
    avail = scrapy.Field()
    domain = scrapy.Field()

下面的pipelines.py

class WhoisPipeline(object):
    def process_item(self, item, spider):
        return item

提前感谢您的所有回复。

【问题讨论】:

  • 有 pipelines.py 文件吗?
  • 是的。这是 pipelines.py 文件中的代码class WhoisPipeline(object): def process_item(self, item, spider): return item

标签: python json web-scraping scrapy web-crawler


【解决方案1】:

parse 函数应该是这样的:

def parse(self, response):
    jsonresponse = json.loads(response.body_as_unicode())
    item = WhoisItem()
    domain_name = list(jsonresponse['domains'].keys())[0]
    item["avail"] = jsonresponse["domains"][domain_name]["avail"]
    item["domain"] = domain_name
    yield item

请注意,我删除了 for 循环。

发生了什么:对于每个响应,您将循环并解析 17 次。 (因此产生 17*17 条记录)

【讨论】:

  • 像魅力一样工作!你太棒了@DeanFenster 非常感谢!
猜你喜欢
  • 2018-07-31
  • 2021-08-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-08-15
相关资源
最近更新 更多