【问题标题】:Scrapy response.xpath not returning anything for a queryScrapy response.xpath 不返回任何查询
【发布时间】:2014-12-01 17:50:55
【问题描述】:

我正在使用scrapy shell 来提取一些文本数据。以下是我在 scrapy shell 中给出的命令:

>>> scrapy shell "http://jobs.parklandcareers.com/dallas/nursing/jobid6541851-nurse-resident-cardiopulmonary-icu-feb2015-nurse-residency-requires-contract-jobs"

>>> response.xpath('//*[@id="jobDesc"]/span[1]/text()')
[<Selector xpath='//*[@id="jobDesc"]/span[1]/text()' data=u'Dallas, TX'>]
>>> response.xpath('//*[@id="jobDesc"]/span[2]/p/text()[2]')
[<Selector xpath='//*[@id="jobDesc"]/span[2]/p/text()[2]' data=u'Responsible for attending assigned nursi'>]
>>> response.xpath('//*[@id="jobDesc"]/span[2]/p/text()[preceding-sibling::*="Education"][following-sibling::*="Certification"]')
[]

第三条命令没有返回任何数据。我试图在命令中的 2 个关键字之间提取数据。我哪里错了?

【问题讨论】:

    标签: shell xpath web-scraping scrapy scrapy-shell


    【解决方案1】:

    //*[@id="jobDesc"]/span[2]/p/text() 会返回一个文本节点列表。您可以在 Python 中过滤相关节点。以下是如何获取 "Education/Experience:""Certification/Registration/Licensure:" 文本段落之间的文本:

    >>> result = response.xpath('//*[@id="jobDesc"]/span[2]/p/text()').extract()
    >>> start = result.index('Education/Experience:')
    >>> end = result.index('Certification/Registration/Licensure:')
    >>> print ''.join(result[start+1:end])
    - Must be a graduate from an accredited school of Nursing.  
    

    UPD(关于 cmets 中的一个附加问题):

    >>> response.xpath('//*[@id="jobDesc"]/span[3]/text()').re('Job ID: (\d+)')
    [u'143112']
    

    【讨论】:

    • 我在这个问题中还有一个小问题。我尝试过这样的事情:>>> jid=response.xpath('//*[@id="jobDesc"]/span[3]/text()').extract() .... 我试过了仅提取数字并删除“Job ID:”......但开始的方式不同......索引不在列表中
    • @crozzfire 当然,这是.re() 的一个很好的用例,请查看答案中的更新。
    【解决方案2】:

    试试:

    substring-before(
      substring-after('//*[@id="jobDesc"]/span[2]/p/text()', 'Education'), 'Certification')
    

    注意:我无法测试它。

    这个想法是您不能使用preceding-siblingfollowing-sibling,因为您查看的是同一个文本节点。您必须使用 substring-before()substring-after() 提取所需的文本部分

    通过结合这两个功能,您可以选择介于两者之间的功能。

    【讨论】:

      猜你喜欢
      • 2017-12-12
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多