空格和选择器

2024-09-26 22:44:16 发布

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

尝试使用ScrapyShell上的选择器从网页中提取信息,但没有成功。我相信这是因为类名中存在空格。知道怎么回事吗?你知道吗

我尝试了不同的语法,比如:

response.xpath('//p[@class="text-nnowrap hidden-xs"]').getall()

response.xpath('//p[@class="text-nnowrap hidden-xs"]/text()').get()

# what I type into my scrapy shell
response.css('div.offer-item-details').xpath('//p[@class="text-nowrap hidden-xs"]/text()').get()

# html code that I need to extract:
<p class="text-nowrap hidden-xs">Apartamento para arrendar: Olivais, Lisboa</p>

预期结果:para arrendar公寓:Olivais,Lisboa

实际结果:[]


Tags: textgetresponse选择器xpathhiddenclasspara
2条回答

class部分中的空白表示有多个类,“text nnowrap”类和“hidden xs”类。为了通过xpath为多个类选择,可以使用以下格式:

"//element[contains(@class, 'class1') and contains(@class, 'class2')]"

(从How to get html elements with multiple css classes抓到这个)

所以在你的例子中,我相信这是可行的。你知道吗

response.xpath("//p[contains(@class, 'text-nnowrap') and contains(@class, 'hidden-xs')]").getall()

在这种情况下,我更喜欢使用css选择器,因为它的语法非常简洁:
response.css("p.text-nowrap.hidden-xs::text")

另外,当你观察html代码时,googlechrome开发工具也会显示css选择器
这使得scraper开发变得更加容易 google developer tools

相关问题 更多 >

    热门问题