【问题标题】:Xpath for div tag exclude span tag and return textdiv标签的Xpath排除span标签并返回文本
【发布时间】:2015-03-03 22:23:12
【问题描述】:

下面的 HTML 代码我需要 xpath

  <div itemtype="http://schema.org/PostalAddress" itemscope="" itemprop="jobLocation">
  <div class="aiDetailJobInfoLabel aiDetailJobInfoLocation">Location: </div>
  <div class="aiDetailJobInfo aiDetailJobInfoLocation">
     <span itemprop="addressLocality">Topeka</span>
      , KS
      <span itemprop="postalCode">66607</span>
  </div>
</div>

在这个 HTML 代码中,我需要输出为 堪萨斯州托皮卡

不应包含 66607

我试过这段代码,但它给了空

 >>> response.xpath('//div[@itemprop="jobLocation"]/div[@class="aiDetailJobInfo aiDetailJobInfoLocation"][not(child::span[@itemprop="postalCode"])]//text()').extract()

如果我写下面的代码,它给了

response.xpath('//div[@itemprop="jobLocation"]/div[@class="aiDetailJobInfo aiDetailJobInfoLocation"]//text()').extract()

output: Topeka, KS, 66607

请帮帮我。

仅供参考: xpath 将与 div text() 一起排除邮政编码,以便返回剩余的 div 和 span 文本。有时,此 div 标签中不存在 postalCode。因此,如果它存在,则跳过它,如果不返回整个 div 标记文本。

【问题讨论】:

    标签: xml xpath scrapy


    【解决方案1】:

    看起来您基本上想要连接目标div 的所有文本节点后代除了postalCode 属性下的那些。相关的文本节点集可以通过类似的 XPath 找到

    //div[@itemprop="jobLocation"]/div[@class="aiDetailJobInfo aiDetailJobInfoLocation"]
       //text()[not(parent::span[@itemProp="postalCode"])]
    

    如果您.extract 这个 XPath,您将获得一个字符串列表(每个文本节点一个),您可以在 Python 级别将它们连接在一起。

    【讨论】:

      【解决方案2】:

      在这里我分享了 2 段代码。你可以拿走任何你需要的东西。

      试试这个:

      response.xpath('//div[@class="aiDetailJobInfo aiDetailJobInfoLocation"]//text()').re(r'[ .a-zA-Z]\w+')
      
      
      
      response.xpath('//div[@class="aiDetailJobInfo aiDetailJobInfoLocation"]//text()').re(r'[a-zA-Z]+')
      
      
      response.xpath('//div[@itemprop="jobLocation"]/div[@class="aiDetailJobInfo aiDetailJobInfoLocation"]//text()').extract()[1:3] 
      

      【讨论】:

      • 感谢您的关注。两者都只返回托皮卡,但我需要托皮卡,堪萨斯州。它不应包括邮政编码。保留 div 标签内的任何文本,所有内容都应该返回。
      • 不错的一个。!我们不能只用 xpath 而不是正则表达式来处理。 ?我打算只使用 xpath。例如,提取没有跨度邮政编码标签的 div 标签文本。
      • 你可以使用切片来得到类似的结果
      • response.xpath('//div[@itemprop="jobLocation"]/div[@class="aiDetailJobInfo aiDetailJobInfoLocation"]//text()').extract()[1:3 ]
      猜你喜欢
      • 2016-05-15
      • 2016-12-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多