json文件不是用Python Scrapy Spid创建的

2024-09-30 18:23:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做的事

我想用Python的Scrapy spider制作json文件。 我目前正在学习“用Python和JavaScript实现数据可视化”。在scraping中,不知道为什么不创建json文件。你知道吗

目录结构

/root
nobel_winners   scrapy.cfg

/nobel_winners:
__init__.py     items.py    pipelines.py    spiders
__pycache__     middlewares.py    settings.py

/nobel_winners/spiders:
__init__.py     __pycache__     nwinners_list_spider.py

工作流程/代码

在nwinners\u列表中输入以下代码_蜘蛛.py诺贝尔奖得主/蜘蛛。你知道吗

#encoding:utf-8

import scrapy

class NWinnerItem(scrapy.Item):
    country = scrapy.Field()

class NWinnerSpider(scrapy.Spider):
    name = 'nwinners_list'
    allowed_domains = ['en.wikipedia.org']
    start_urls = ["https://en.wikipedia.org/wiki/List_of_Nobel_laureates_by_country"]

    def parse(self, response):

        h2s = response.xpath('//h2')

        for h2 in h2s:
            country = h2.xpath('span[@class="mw-headline"]/text()').extract()

在根目录中输入以下代码。你知道吗

scrapy crawl nwinners_list -o nobel_winners.json

错误

出现以下显示,json文件中没有输入任何数据。你知道吗

2018-07-25 10:01:53 [scrapy.core.engine] INFO: Spider opened
2018-07-25 10:01:53 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)

我试过的

1.在文本中,这是一个较长的来源,但我只检查了'国家'变量。你知道吗

2.我进入了胶状外壳,用基于IPython的外壳检查了每个外壳的运动。而且它被确认价值是坚定的在'国家'。你知道吗

h2s = response.xpath('//h2')

for h2 in h2s:
    country = h2.xpath('span[@class="mw-headline"]/text()').extract()
    print(country)

Tags: 文件代码pyjsonitemsh2countryxpath
1条回答
网友
1楼 · 发布于 2024-09-30 18:23:26

尝试使用以下代码:

import scrapy

class NWinnerItem(scrapy.Item):
    country = scrapy.Field()

class NWinnerSpider(scrapy.Spider):
    name = 'nwinners_list'
    allowed_domains = ['en.wikipedia.org']
    start_urls = ["https://en.wikipedia.org/wiki/List_of_Nobel_laureates_by_country"]

    def parse(self, response):

        h2s = response.xpath('//h2')

        for h2 in h2s:
            yield NWinnerItem(
                country = h2.xpath('span[@class="mw-headline"]/text()').extract_first()
            )

然后跑 scrapy crawl nwinners_list -o nobel_winners.json -t json


在回调函数中,解析响应(网页)并返回包含提取的数据、项对象、请求对象的dict,或这些对象的iterable。See scrapy documentation

这就是为什么有0件物品被刮走的原因,你需要退货!你知道吗

还要注意,.extract()返回基于xpath查询的列表,.extract_first()返回列表的第一个元素。你知道吗

相关问题 更多 >