【问题标题】:How to extract text which lies after <strong> tag in element如何提取元素中 <strong> 标记之后的文本
【发布时间】:2018-11-06 11:36:13
【问题描述】:

尝试从如下所示的元素中提取文本:

<div><strong>"Beginning_of_text"</strong>"Rest_of_text"</div>

当我尝试使用 Scrapy shell 提取 "Rest_of_text"

response.css("div::text").extraxt()

它什么也没给我。我是否必须使用一些特殊命令来获取位于元素内 &lt;strong&gt; 标记之后的文本?

【问题讨论】:

  • 试试response.xpath("//div/text()").extract()response.xpath("//div/strong/following-sibling::text()").extract()
  • "Beginning_of_text" : response.css("div strong::text").extract() 也许?
  • 尝试使用response.css("div::text").extract() 代替response.css("div::text").extraxt() 以获得"Rest_of_text" 作为结果。 scrapy中没有.extraxt()这样的东西。

标签: python web-scraping scrapy


【解决方案1】:

只有“Rest_of_text”你可以使用response.xpath('//div/strong/following-sibling::text()').get()

【讨论】:

    【解决方案2】:

    鉴于您提供的文本,您提到的命令应该返回以下内容:

    ['"Rest_of_text"']
    

    如果strong标签前有空格,可能会出现问题,例如:

    <div>   <strong>"Beginning_of_text"</strong>"Rest_of_text"</div>
    

    在这种情况下,如果你执行相同的命令,你会得到这个:

    ['   ', '"Rest_of_text"']
    

    但如果strong 标签后面没有任何内容,你会得到这个:

    ['   ']
    

    我知道处理所有这些情况的最佳方法是执行以下操作:

    >>> full_text = ''.join(response.xpath('//div//text()').extract())
    >>> before_strong, after_strong = full_text.split(response.css('strong::text').extract_first())
    

    所以在您提供的文本中,before_strong 将等于 ''after_strong 将等于 '"Rest_of_text"',这似乎是您想要得到的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-21
      • 1970-01-01
      • 2016-12-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多