【发布时间】: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()')
}
【问题讨论】: