【问题标题】:How to get innerHTML of a node using scrapy Selector?如何使用scrapy Selector获取节点的innerHTML?
【发布时间】:2015-04-23 20:20:48
【问题描述】:

假设有一些 html 片段,例如:

<a>
   text in a
   <b>text in b</b>
   <c>text in c</c>
</a>
<a>
   <b>text in b</b>
   text in a
   <c>text in c</c>
</a>

我想提取标签内的文本,但不包括那些标签,同时保留它们的文本,例如,我想在上面提取的内容就像“b 中的文本 c 中的文本”和“b 中的文本”文本公司中的文本”。现在我可以使用scrapy Selector css() 函数获取节点,那么我该如何处理这些节点以获得我想要的?任何想法将不胜感激,谢谢!

【问题讨论】:

    标签: python html xpath css-selectors scrapy


    【解决方案1】:

    试试这个

    response.xpath('//a/node()').extract()
    

    【讨论】:

    • 这是最好和最安全的解决方案。
    【解决方案2】:

    在scrapy 1.5中,你可以使用/*来获取innerhtml。 示例:

    content = response.xpath('//div[@class="viewbox"]/div[@class="content"]/*').extract_first()
    

    【讨论】:

    • 这只会提取 .content 中的第一个节点,使用 extract() 和 ''.join 来获取完整的 innerhtml 作为字符串。
    【解决方案3】:

    您可以在您选择的元素上使用XPath's string() 函数:

    $ python
    >>> import scrapy
    >>> selector = scrapy.Selector(text="""<a>
    ...    text in a
    ...    <b>text in b</b>
    ...    <c>text in c</c>
    ... </a>
    ... <a>
    ...    <b>text in b</b>
    ...    text in a
    ...    <c>text in c</c>
    ... </a>""", type="html")
    >>> for link in selector.css('a'):
    ...     print link.xpath('string(.)').extract()
    ... 
    [u'\n   text in a\n   text in b\n   text in c\n']
    [u'\n   text in b\n   text in a\n   text in c\n']
    >>> 
    

    【讨论】:

      【解决方案4】:

      这是我设法做到的:

      from scrapy.selector import Selector
      
      sel = Selector(text = html_string)
      
      for node in sel.css('a *::text'):
          print node.extract()
      

      假设html_string 是一个变量,其中包含您问题中的 html,此代码会产生以下输出:

         text in a
      
      text in b
      
      
      text in c
      
      
      
      
      text in b
      
         text in a
      
      text in c
      

      选择器a *::text() 匹配作为a 节点后代的所有文本节点。

      【讨论】:

      • 这很棒,但我设法通过 sel.css("a").extract() 做到了,然后使用正则表达式排除了那些 html 标签
      • @kuixiong 太好了!注意,用正则表达式解析HTML一般是not considered a good practice。如果您控制该 HTML 并且它足够简单,请继续使用正则表达式。否则,请考虑使用专门的工具。
      • 解决方案收集文本,而不是innerHTML。
      猜你喜欢
      • 2012-06-09
      • 1970-01-01
      • 2016-04-20
      • 2017-11-09
      • 2023-03-19
      • 2014-12-25
      • 2012-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多