【问题标题】:Xpath expression for text that contains a certain string包含特定字符串的文本的 Xpath 表达式
【发布时间】:2017-04-25 16:05:25
【问题描述】:

http://www.apkmirror.com/apk/redditinc/reddit/reddit-1-5-5-release/reddit-1-5-5-android-apk-download/ 网站上,我试图提取包含Min:Target: 版本的Android 的行(见下面的屏幕截图)。

在 Scrapy shell 中,到目前为止我已经想出了 XPath 表达式

In [1]: android_version = response.xpath('//*[@title="Android version"]/following-sibling::*[@class="appspec-value"]')

这样,如果我将 .//text()extract() 连接起来,我会得到几行,包括我想要的:

In [2]: android_version_text = android_version.xpath('.//text()').extract()

In [3]: android_version_text
Out[3]: 
[u'\n',
 u'Min: Android 4.0.3 (Ice Cream Sandwich MR1, API 15) ',
 u'\n',
 u'Target: Android 6.0 (Marshmallow, API 23)',
 u'\n']

我现在想优化 XPath 表达式以仅获取具有 text() 且包含 "Min:""Target: 的字段。关注XPath contains(text(),'some string') doesn't work when used with node with more than one Text subnode,我试过了

In [7]: android_version.xpath('.//*[contains(text(), "Min:"]')

但这会产生一个

ValueError: XPath error: Invalid expression in .//*[contains(text(), "Min:"]

例如,我如何构造一个 XPath 表达式以仅获取 Min: 行?

【问题讨论】:

    标签: python xpath scrapy


    【解决方案1】:

    https://blog.scrapinghub.com/2014/07/17/xpath-tips-from-the-web-scraping-trenches/ 之后,我想出了以下内容:

    In [12]: android_min_version = response.xpath('//*[@title="Android version"]/following-sibling::*[@class="appspec-value"]//text()[starts-with(., "Min:")]')
    
    In [13]: android_min_version.extract()
    Out[13]: [u'Min: Android 4.0.3 (Ice Cream Sandwich MR1, API 15) ']
    

    简而言之,要过滤你想要的文本,你需要一个普通的//text(),后跟一个[contains(., "target_string")],其中"target_string" 是你正在搜索的字符串。 (这里我也用starts-with代替contains)。

    【讨论】:

      猜你喜欢
      • 2015-04-10
      • 1970-01-01
      • 2020-08-15
      • 2023-03-18
      • 1970-01-01
      • 2010-10-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多