【问题标题】:Nokogiri returning empty arrayNokogiri 返回空数组
【发布时间】:2015-11-19 10:01:53
【问题描述】:

我正在抓取屏幕http://www.weather.com/weather/hourbyhour/l/INXX0202:1:IN

我尝试选择同时使用 CSS 和 XPath 来获取网站中表格的降水预报部分。

它们都不能在我的程序中工作,因为它们返回空数组,但是,它们都可以在 Chrome 开发工具中工作(检查元素 -> 控制台 -> CSS 为 $$,Xpath 为 $x)。

为什么会这样?跟命名空间有关系吗?

require 'open-uri'
require 'nokogiri'
foo = Nokogiri::HTML(open("http://www.weather.com/weather/hourbyhour/l/INXX0202:1:IN"))
foo.remove_namespaces!
p foo.xpath("//section[@data-ng-class]/p[@class='precip weather-cell ng-isolate-scope']/span[@data-ng-if]") # returns []
p foo.css("section[data-ng-class] p[class='precip weather-cell ng-isolate-scope'] span[data-ng-if]")  # returns []

这是a screenshot of the website,我正在尝试从中获取数据。我想要的是“Precip”标题下的数字(例如:图片中的 85,100,100,95,80,70,45,40)。

我将页面的 HTML 复制到本地 HTML 文件中,并让我的程序访问该文件。然后程序给了我所需的输出,但是当我让同一个程序使用 OpenUri 访问网站时,它返回一个空数组:

require 'open-uri'
require 'nokogiri'
foo = open("http://www.weather.com/weather/hourbyhour/l/INXX0202:1:IN")
nokogirifoo = Nokogiri::HTML(foo)
p nokogirifoo.xpath("//section[@data-ng-class]/p[@class='precip weather-cell ng-isolate-scope']/span[@data-ng-if]") # => empty array

bar = File.open('weather.html') # weather.html is just the html code of the page copied into a local file
nokogiribar = Nokogiri::HTML(bar)
p nokogiribar.xpath("//section[@data-ng-class]/p[@class='precip weather-cell ng-isolate-scope']/span[@data-ng-if]").text # => "85%100%100%95%80%70%45%40%" (this is what I need)

这是 HTML 的 sn-p(显示的部分嵌套在网站的多个标签中):

 <section class="wxcard-hourly summary-view ng-isolate-scope last" data-ng-class="{'last': $last}" data-wxcard-hourly="hour" data-wxcard-hourly-methods="hourlyScope" data-hours-index="hoursDataIndex" data-show-wx-labels="false" data-details-view="false">
    <div class="heading weather-cell" data-ng-switch="dataMethods.checkTime(data.getForecastLocalDate())">
        <h2>

      <span class="wx-dsxdate ng-binding ng-scope" ng-bind-template=" 9:30 am" data-dsxdate="" data-ng-switch-when="min" data-datetime="data.getForecastLocalDate()" data-timezone="locTz" data-format="'h:mm a'"> 9:30 am</span>
        </h2>
    <span class="sub-heading wx-hourly-date wx-dsxdate ng-binding ng-scope" ng-bind-template=" Fri, Nov 20" data-dsxdate="" data-datetime="data.getForecastLocalDate()" data-timezone="locTz" data-format="'EEE, MMM d'"> Fri, Nov 20</span>
    </div>
    <p class="hi-temp temp-1 weather-cell ng-isolate-scope" data-wx-temperature="data.getTemp()" data-show-temp-unit="hoursIndex === 0"> <span data-ng-if="hasValue()" data-ng-bind="temp" class="ng-binding ng-scope">28</span><sup data-ng-if="hasValue()" class="deg ng-scope">°</sup><sup class="temp-unit ng-binding ng-scope" data-ng-if="showTempUnit" data-ng-bind="tempUnit()">C</sup>
</p>
    <p class="feels-like temp-2 weather-cell ng-isolate-scope" data-wx-temperature="data.getFeelsLike()" data-temp-prefix="Feels"><span ng-if="tempPrefix" class="temp-prefix ng-binding ng-scope" data-ng-bind="tempPrefix">Feels</span><span data-ng-if="hasValue()" data-ng-bind="temp" class="ng-binding ng-scope">34</span><sup data-ng-if="hasValue()" class="deg ng-scope">°</sup>
</p>
    <div class="weather-cell">
        <h3 class="weather-phrase">
            <div class="weather-icon ng-isolate-scope wx-weather-icon" data-wxicon="" data-sky-code="data.getSkyCode()"><div class="svg-icon"><img src="/sites/all/modules/custom/angularmods/app/shared/wxicon/svgz/thunderstorm.svgz?1" aria-hidden="true" alt="thunderstorm"></div></div>

            <span class="phrase ng-binding" data-ng-bind-template="Thunderstorms">Thunderstorms</span>
        </h3>
    </div>
    <!-- The Next Line Is What I Need-->
    <p class="precip weather-cell ng-isolate-scope" data-wx-precip="dataMethods.roundedValue(data.getChanceOfPrecipDay())" data-wx-precip-type="data.getPrecipType()" data-wx-precip-sky-code="data.getSkyCode()"><span aria-hidden="true" class="wx-iconfont-global wx-icon-precip-rain-1"></span><span data-ng-if="!wxPrecipIconOnly" class="precip-val ng-binding ng-scope" data-ng-bind="chanceOfPrecip() | safeDisplay">85%</span></p>

    <p class="humidity-wrapper weather-cell">
      <span data-ng-bind-template="85%" class="humidity ng-binding ng-isolate-scope" data-wx-percentage="data.getHumidity()">85%</span>
    </p>

    <p class="wind-conditions weather-cell">
        <span class="wx-wind ng-binding ng-isolate-scope" data-ng-bind-template="ESE 9 km/h" data-wx-wind-direction="data.getWindDirectionText()" data-wx-wind-speed="data.getWindSpeed()">ESE 9 km/h</span>
    </p>
</section>

【问题讨论】:

  • 欢迎来到 Stack Overflow。请不要让我们去一个站点并挖掘 HTML;您需要提取 minimal HTML 来演示您正在使用的内容并将其放入您的问题中。向我们提供您要收集的数据的示例。请阅读“How to Ask”。使用短选择器比长选择器更容易定位数据。将其分解成小块,看看您是否可以通过这种方式获取数据。
  • @theTinMan 感谢您的意见。请看一下我编辑的帖子。为了准确起见,我的选择器有点长,并且只提取我需要的数据。然而,话虽如此,我会寻找更短、更好的方法来获取相同的数据。我尝试分解选择器,但这也不起作用。

标签: css ruby xpath nokogiri open-uri


【解决方案1】:

问题在于您正在使用浏览器查看页面,该页面除了实现 HTML 解析器外,还具有嵌入式 JavaScript 解释器。浏览器会查找并处理任何 JavaScript &lt;script&gt; 标签,在为用户呈现页面之前加载和调整元素。这就是您想要的页面中发生的事情。解析器,如 Nokogiri,是 NOT 浏览器,并且不关心嵌入的脚本,因为在 HTML 中,脚本只是特定标签内的文本,因此,您可以使用辅助 HTML want 永远不会被检索到。

您说您将 HTML 保存到文件中,但是,您没有说 如何 保存它。我猜,因为保存的 HTML 包含您想要的信息,所以它是使用浏览器保存的。

处理网页时,第一步是确定页面是使用动态 HTML 和/或 JavaScript 还是静态 HTML。关闭浏览器中的 JavaScript,然后加载 URL。或者,您可以从命令行使用wgetcurl 来检索页面并使用编辑器查看它。无论哪种情况,您都看到了您想要的内容吗?如果是这样,那么很有可能你可以在检索到它之后使用像 Nokogiri 这样的解析器来处理它。如果你不这样做,那么你必须使用可以解释 JavaScript、处理加载的信息,然后将其传递给解析器的东西。

PhantomJS 和 Watir 等工具可以帮助您,或者,您可以找到一个气象服务,让您可以使用 API 来检索数据而无需抓取,因为抓取总是非常脆弱。

还可以找出 JavaScript 使用哪个 URL 来检索数据,然后请求辅助资源并对其进行解析。它可能是 HTML,或者它可能是包含数据的 JSON,然后由 JavaScript 处理,然后动态构建整个表。

Stack Overflow 上有很多问题和答案都在讨论如何完成上述所有操作。

总而言之,一旦你得到你想要的 HTML,你就可以轻松地减少这些值所需的 CSS 选择器。每个值都包含在具有类的&lt;style&gt; 标记中,因此请使用该类来查找值。

require 'nokogiri'
doc = Nokogiri::HTML(<<EOT)

    <section class="wxcard-hourly summary-view ng-isolate-scope last" data-ng-class="{'last': $last}" data-wxcard-hourly="hour" data-wxcard-hourly-methods="hourlyScope" data-hours-index="hoursDataIndex" data-show-wx-labels="false" data-details-view="false">
        <div class="heading weather-cell" data-ng-switch="dataMethods.checkTime(data.getForecastLocalDate())">
            <h2>

          <span class="wx-dsxdate ng-binding ng-scope" ng-bind-template=" 9:30 am" data-dsxdate="" data-ng-switch-when="min" data-datetime="data.getForecastLocalDate()" data-timezone="locTz" data-format="'h:mm a'"> 9:30 am</span>
            </h2>
        <span class="sub-heading wx-hourly-date wx-dsxdate ng-binding ng-scope" ng-bind-template=" Fri, Nov 20" data-dsxdate="" data-datetime="data.getForecastLocalDate()" data-timezone="locTz" data-format="'EEE, MMM d'"> Fri, Nov 20</span>
        </div>
        <p class="hi-temp temp-1 weather-cell ng-isolate-scope" data-wx-temperature="data.getTemp()" data-show-temp-unit="hoursIndex === 0"> <span data-ng-if="hasValue()" data-ng-bind="temp" class="ng-binding ng-scope">28</span><sup data-ng-if="hasValue()" class="deg ng-scope">°</sup><sup class="temp-unit ng-binding ng-scope" data-ng-if="showTempUnit" data-ng-bind="tempUnit()">C</sup>
    </p>
        <p class="feels-like temp-2 weather-cell ng-isolate-scope" data-wx-temperature="data.getFeelsLike()" data-temp-prefix="Feels"><span ng-if="tempPrefix" class="temp-prefix ng-binding ng-scope" data-ng-bind="tempPrefix">Feels</span><span data-ng-if="hasValue()" data-ng-bind="temp" class="ng-binding ng-scope">34</span><sup data-ng-if="hasValue()" class="deg ng-scope">°</sup>
    </p>
        <div class="weather-cell">
            <h3 class="weather-phrase">
                <div class="weather-icon ng-isolate-scope wx-weather-icon" data-wxicon="" data-sky-code="data.getSkyCode()"><div class="svg-icon"><img src="/sites/all/modules/custom/angularmods/app/shared/wxicon/svgz/thunderstorm.svgz?1" aria-hidden="true" alt="thunderstorm"></div></div>

                <span class="phrase ng-binding" data-ng-bind-template="Thunderstorms">Thunderstorms</span>
            </h3>
        </div>
        <!-- The Next Line Is What I Need-->
        <p class="precip weather-cell ng-isolate-scope" data-wx-precip="dataMethods.roundedValue(data.getChanceOfPrecipDay())" data-wx-precip-type="data.getPrecipType()" data-wx-precip-sky-code="data.getSkyCode()"><span aria-hidden="true" class="wx-iconfont-global wx-icon-precip-rain-1"></span><span data-ng-if="!wxPrecipIconOnly" class="precip-val ng-binding ng-scope" data-ng-bind="chanceOfPrecip() | safeDisplay">85%</span></p>

        <p class="humidity-wrapper weather-cell">
          <span data-ng-bind-template="85%" class="humidity ng-binding ng-isolate-scope" data-wx-percentage="data.getHumidity()">85%</span>
        </p>

        <p class="wind-conditions weather-cell">
            <span class="wx-wind ng-binding ng-isolate-scope" data-ng-bind-template="ESE 9 km/h" data-wx-wind-direction="data.getWindDirectionText()" data-wx-wind-speed="data.getWindSpeed()">ESE 9 km/h</span>
        </p>
    </section>
EOT

从简单的搜索开始:

doc.at('.precip-val').text # => "85%"

at 找到第一个匹配的节点并将其返回。 text 检索其文本节点。

您需要该类的多个节点,所以这样的事情应该会有所帮助:

doc.search('.precip-val').map(&:text) # => ["85%"]

search查找所有匹配的节点并返回一个NodeSet,它就像一个数组,可以使用map进行迭代。

他们不太可能将.precip-val 用于包装值的非降水标签,但是,如果他们这样做了,请尝试:

doc.search('span.precip-val').map(&:text)

看看你会得到什么。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-05-17
    • 1970-01-01
    • 2017-07-12
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多