【问题标题】:Empty .json file空的 .json 文件
【发布时间】:2018-12-02 17:52:51
【问题描述】:

我编写了这个简短的蜘蛛代码来从黑客新闻首页(http://news.ycombinator.com/) 中提取标题。

import scrapy

class HackerItem(scrapy.Item): #declaring the item
    hackertitle = scrapy.Field()


class HackerSpider(scrapy.Spider):
    name = 'hackernewscrawler'
    allowed_domains = ['news.ycombinator.com'] # website we chose
    start_urls = ['http://news.ycombinator.com/']

   def parse(self,response):
        sel = scrapy.Selector(response) #selector to help us extract the titles
        item=HackerItem() #the item declared up

# xpath of the titles
        item['hackertitle'] = 
sel.xpath("//tr[@class='athing']/td[3]/a[@href]/text()").extract()


# printing titles using print statement.
        print (item['hackertitle']

但是当我运行代码scrapy scrawl hackernewscrawler -o hntitles.json -t json

我得到一个没有任何内容的空 .json 文件。

【问题讨论】:

    标签: scrapy web-crawler


    【解决方案1】:

    您应该将print 语句更改为yield

    import scrapy
    
    class HackerItem(scrapy.Item): #declaring the item
        hackertitle = scrapy.Field()
    
    
    class HackerSpider(scrapy.Spider):
        name = 'hackernewscrawler'
        allowed_domains = ['news.ycombinator.com'] # website we chose
        start_urls = ['http://news.ycombinator.com/']
    
        def parse(self,response):
            sel = scrapy.Selector(response) #selector to help us extract the titles
            item=HackerItem() #the item declared up
    
    # xpath of the titles
            item['hackertitle'] = sel.xpath("//tr[@class='athing']/td[3]/a[@href]/text()").extract()
    
    
    # return items
            yield item
    

    然后运行:

    scrapy crawl hackernewscrawler -o hntitles.json -t json
    

    【讨论】:

    • 在这种情况下,因为只是一个结果,您可以将 yield 更改为 return
    猜你喜欢
    • 1970-01-01
    • 2017-06-14
    • 2016-03-06
    • 2016-02-06
    • 2021-06-22
    • 2019-07-26
    • 1970-01-01
    • 2020-07-16
    • 2019-01-16
    相关资源
    最近更新 更多