【问题标题】:Xpath vs. CSS selector in Scrapy: Why is data stored differently?Scrapy 中的 Xpath 与 CSS 选择器:为什么数据存储方式不同?
【发布时间】:2019-02-13 06:57:30
【问题描述】:

我可以使用两种不同的方法来提取文章的标题:xpath 与 css。他们会给我相同的结果,但有一个区别。使用 xpath 会将数据(json 文件)存储在方括号 ["Some Title"] 中,而 css 选择器将仅存储不带括号的数据 "Some Title"。我实际上不想用括号存储数据。 如何使用 xpath 做到这一点?

这是我提取文档标题的代码:

CSS 选择器

def parse_article(self, response):
    def extract_with_css(query):
        return response.css(query).get(default='').strip() 


    yield {
        'title': extract_with_css('div#title h2::text')           
          }

Xpath

 def parse_article(self, response):
    def extract_with_xpath(query):
        return response.xpath(query).extract() 


    yield {
        'title': extract_with_xpath('//div[@id="title"]/h2/text()') 
          }

【问题讨论】:

    标签: python json scrapy


    【解决方案1】:

    将您的代码从extract() 编辑为get()

    def extract_with_xpath(query):
        return response.xpath(query).get(default='').strip() 
    

    方法extract返回所有匹配,get只返回第一个。

    【讨论】:

    • 真的可以根据我要提取的数据同时使用这两种方法吗?假设对于“标题”,我只想进行第一场比赛(就像您描述的那样),但是对于例如“关键字”(存储在头部的元标记中)我想要所有匹配项。当然你的方法有效,但实际上只有一个标题,但更多的关键字。现在,我只得到第一个关键字。
    • 创建另一个语法糖,以便在需要的地方提取和使用。例如,将extract_with_xpathextract 一起使用,并为get 创建get_with_xpath 。在extract 中,您可以使用' '.join([i.strip() for i in response.xpath(query).extract()]) 之类的内容。
    • 或者只使用清晰的语法,没有任何额外的功能。
    • 对!我开始更好地理解。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-04-23
    • 2013-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 1970-01-01
    • 2018-08-08
    • 1970-01-01
    相关资源
    最近更新 更多