【问题标题】:How to get Nokogiri to scrape text from span in Ruby如何让 Nokogiri 在 Ruby 中从 span 中抓取文本
【发布时间】:2015-08-17 12:45:04
【问题描述】:

我正在尝试使用 Nokogiri 和 Curb 从网站上抓取信息,但我似乎无法找到正确的名称/来查找要抓取的位置。我正在尝试抓取位于 HTML 代码底部的 API 密钥为“xxxxxxx”。

HTML代码是:

    <body class="html not-front logged-in no-sidebars page-app page-app- page-app-8383900 page-app-keys i18n-en" data-twttr-rendered="true">

    <div id="skip-link"></div>
    <div id="page-wrapper">
        <!--

         Code for the global nav 

        -->
        <nav id="globalnav" class="without-subnav"></nav>
        <nav id="subnav"></nav>
        <section id="hero" class="hero-short"></section>

<section id="gaz-content">

    <div class="container">
        ::before
        <div id="messages"></div>
        <div id="gaz-content-wrap-outer" class="row">
            ::before
            <div id="gaz-content-wrap-inner" class="span12">
                <div class="row">
                    ::before
                    <div class="article-wrap span12">
                        <article id="gaz-content-body" class="content">
                            <header></header>
                            <div class="header-action"></div>
                            <div class="tabs"></div>

lass="d-block d-block-system g-main">

    <div class="app-details">
        <h2>

            Application Settings

        </h2>
        <div class="description"></div>
        <div class="app-settings">
            <div class="row">
                ::before
                <span class="heading">

                    Consumer Key (API Key)

                </span>
                <span>

                    xxxxxxxxx

                </span>

我似乎只能得到“内容”文本。

我的代码如下:

consumer = html.at("#gaz-content-body")['class']
puts consumer

我不确定要输入什么来选择类和/或跨越输入文本。我能得到的只是 Nokogiri 放入“内容”。

【问题讨论】:

  • 您的 HTML 无效。请阅读“MCVE”。我们需要最少的输入数据来证明问题中的问题。解析器要么拒绝格式错误的输入,要么尝试修复它,但修复它会改变它,使任何得到的答案都不能正确地适合问题。

标签: html ruby web-scraping nokogiri curb


【解决方案1】:

在这种情况下,我们需要在span class="heading" 之后和div class="app-settings" 内部找到第二个span - 我有点笼统但不过分。我使用search 而不是at 来检索两个跨度并获得第二个:

# Gets the 2 span elements under <div class='app-settings'>.
res = html.search('#gaz-content-body .app-settings span')

# Use .text to get the contents of the 2nd element.
res[1].text.strip
# => "xxxxxxxx"

但您也可以使用at 来定位相同的目标:

res = html.at("#gaz-content-body .app-settings span:nth-child(2)")
res.text.strip
# => "xxxxxxxx"

【讨论】:

  • 这些似乎都不起作用,我得到一个空白输出或错误读取“nil:NilClass (NoMethodError) 的未定义方法‘文本’”
  • 抱歉,它应该适用于您提供的文档部分。您介意提供整个文件吗?
  • 好的。它为html.at("#gaz-content-body")['class'] 提供“内容”,而我给的错误则为,对吧?
  • 你说你要么得到一个空白输出,要么得到一个错误,你能告诉我你什么时候得到它们吗?我的意思是做导致空白的事情和做导致错误的事情。
  • 答案是 "puts page.css("span")[5].text" 它会给我 xxxxx @limekin
猜你喜欢
  • 1970-01-01
  • 2019-12-23
  • 1970-01-01
  • 1970-01-01
  • 2019-02-13
  • 1970-01-01
  • 2013-09-30
  • 2011-08-07
  • 2017-03-06
相关资源
最近更新 更多