【问题标题】:Xpath getting text with mixed elements in same divXpath在同一div中获取具有混合元素的文本
【发布时间】:2018-07-08 08:00:07
【问题描述】:

这里是一些示例 HTML

<div class="something">
  <p> This is a <b> Paragraph </b> with <a href="/something"> mixed </a> elements
 <p> Next paragraph....
</div>

我尝试的是

//div[contains('@class','something')/text()

//div[contains('@class','something')/*/text()

//div[contains('@class','something')/p/text()

所有这些似乎都跳过了“b”标签和“a”标签。

【问题讨论】:

    标签: xpath web-scraping scrapy screen-scraping


    【解决方案1】:

    尝试" ".join(sel.xpath("//div[contains(@class,'something')]//text()").extract()),其中sel 是选择器,在您的情况下可能是response

    【讨论】:

      【解决方案2】:

      使用 XPath 表达式

      //div[contains(@class,'something')]//text()
      

      获取所选div 元素中所有text() 节点的文本的串联。

      输出:

      This is a  Paragraph  with  mixed  elements  
      Next paragraph....
      

      【讨论】:

        【解决方案3】:

        这取决于您想要获得什么以及如何获得。无论如何,您尝试的方法存在几个问题:

        • XPath 表达式中 contains 后面缺少右括号 (])。
        • @classcontains 中使用时不应包含在(单)引号中。

        如果你想将div元素的所有文本作为一个字符串,你可以使用

        normalize-space(//div[contains(@class,'something')])
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2012-01-26
          • 1970-01-01
          • 2022-11-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多