【问题标题】:Split content in Nokogiri when tags are encountered遇到标签时在 Nokogiri 中拆分内容
【发布时间】:2015-04-20 01:05:12
【问题描述】:

鉴于 HTML 页面的以下部分,我希望能够将“我们”和“约翰”分开对待。

            <div id="ad-description" class="c-clear c-word-wrap">

Room for rent in Sydney.
<br/><br/>For more information please contact us<br/>John :- 0491 570 156<br/>Jane :- (02) 5550 1234</div>

    <!-- google_ad_section_end(name=description) -->
        </div>

当使用 Nokogiri 访问广告描述节点,然后在该节点上调用 content 时,我得到 usJohn 作为结果字符串的一部分:

document = Nokogiri::HTML(text)
ad_description_xpath = './/div[contains(@id, "ad-description")]'
ad_description_nodes = document.xpath(ad_description_xpath)
ad_description_node = ad_description_nodes.first
ad_description_node.content # "...please contact usJohn :- ..."

如何让 Nokogiri 返回一个在“us”和“John”之间带有某种空格的字符串,或者在单独的字符串中使用“us”和“John”?

理想情况下,所采用的方法将能够处理节点内的任何标签,而我编写的代码不必提及特定标签。

【问题讨论】:

    标签: ruby web-scraping nokogiri


    【解决方案1】:

    text() 节点选择器将选择文本节点,这将为您提供各自节点中的每个文本部分。然后您可以使用map 来获取字符串数组:

    document = Nokogiri::HTML(text)
    # Note text() added to end of XPath here:
    ad_description_nodes = document.xpath('.//div[contains(@id, "ad-description")]/text()'
    
    strings = ad_description_nodes.map &:content
    

    使用您的示例数据,strings 现在看起来像:

    ["\n\nRoom for rent in Sydney.\n", "For more information please contact us", "John :- 0491 570 156", "Jane :- (02) 5550 1234"]
    

    如您所见,您可能会得到一些额外的前导或尾随空格,以及一些仅由空格组成的节点,因此您可能需要更多处理。这也会错过任何不是 div 直接子级的文本,例如如果strongem 标签中有一些文本。如果有可能,您可以使用//text() 而不是/text()

    【讨论】:

      【解决方案2】:

      你可以调用#children获取ad_description_node的子节点,然后用text?过滤文本节点。这样,您将在ad_description_node 内拥有一组文本节点:

      ad_description_node.children.select( &:text? ).map( &:content )
      
      # [
      #   [0] "\n\n  Room for rent in Sydney.\n  ",
      #   [1] "For more information please contact us",
      #   [2] "John :- 0491 570 156",
      #   [3] "Jane :- (02) 5550 1234"
      # ]
      

      【讨论】:

        猜你喜欢
        • 2021-06-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-04-19
        相关资源
        最近更新 更多