2017-05-08 193 views
1

在Scrapy壳为http://www.apkmirror.com/apk/airbnb-inc/airbnb/的元件的某些类的元素,我试图提取对应于制作的Airbnb应用程序的不同版本的链接:CSS/Xpath的选择器,用于用含有某些文本

enter image description here

由于使用Chrome的检查看到,这个元素的结构是:

enter image description here

与类的listWidget的孩子包含我想要提取的链接。所以,我想先选择“带有类listWidget的元素,其中包含一个包含文本”所有版本“的元素。”

到目前为止,我想出了

In [4]: response.css('.listWidget').xpath('.//*[contains(text(), "All versions")]').extract() 
Out[4]: [u'<div class="widgetHeader">All versions </div>'] 

然而,这个选择变为“太远”:我想选择listWidget包含此元素,而不是元素本身。我该如何做到这一点?

回答

2

您可以尝试使用下面XPath表达:

.//div[div[text()="All versions "]] 

这将匹配div包含divtext"All versions "

+0

这似乎做什么,我问:在我的Scrapy壳,如果我尝试'response.xpath( '.// DIV [DIV [文本()= “所有版本”]]')提取物() '',我得到'[''

\n
All versions
\ n
']',这是'div'用给定的文字包围'div'。 (它不包含'appRow' div,但是这是因为我问了一个错误的问题:我实际上对'div'的两个层次感兴趣)。 –

+1

如果你想匹配'appRow',你可能需要尝试'.//div[div[text()="All versions“]]/following-sibling :: div [@ class =”appRow“]' – Andersson

+0

Yes ,我最终使用了这种方法,并使用CSS选择器代替Xpath选择器来选择遵循Scrapy推荐实践的类(https://doc.scrapy.org/zh/latest/topics/selectors.html#when-querying-by )使用CSS的-class-考虑 - 。我用来获得三个链接的最后一个表达式是'response.xpath('.//* [* [contains(text(),“All versions”)]]/following-sibling :: *')。css(' .appRow ')。CSS('。downloadLink ')。的xpath(' .//@ HREF')。提取物()'。 –

1

还有的XPath's contains()在Scrapy一个CSS版本(事实上,it's in cssselect) 。

从OP的评论in @Andersson's answer

最终的表达经常拿这三个环节是

response.xpath('.//*[*[contains(text(), "All versions")]]/following-sibling::*').css('.appRow').css('.dow‌​nloadLink').xpath('.‌​//@href').extract() 

一个可以转换,为:

In [6]: response.css(''':contains("All versions") ~ .appRow 
          .downloadLink::attr(href)''').extract() 

这输出:

Out[6]: 
['/apk/airbnb-inc/airbnb/airbnb-17-14-release/', 
'/apk/airbnb-inc/airbnb/airbnb-17-12-release/', 
'/apk/airbnb-inc/airbnb/airbnb-17-11-release/']