2

我正在使用 Nokogiri 打开有关各个国家的维基百科页面,然后从跨维基链接(外语维基百科的链接)中提取这些国家的其他语言名称。但是,当我尝试打开France 的页面时,Nokogiri 没有下载完整页面。也许它太大了,反正它不包含我需要的跨维基链接。我怎样才能强制它全部下载?

这是我的代码:

url = "http://en.wikipedia.org/wiki/" + country_name
page = nil
begin
  page = Nokogiri::HTML(open(url))
rescue   OpenURI::HTTPError=>e
  puts "No article found for " + country_name
end

language_part = page.css('div#p-lang')

测试:

with country_name = "France"
=> []

with country_name = "Thailand"
=> really long array that I don't want to quote here,
   but containing all the right data

也许这个问题超出了 Nokogiri 并进入了 OpenURI——无论如何我需要找到一个解决方案。

4

3 回答 3

9

Nokogiri 不检索页面,它要求 OpenURI 使用readOpen::URI 返回的 StringIO 对象的内部来执行此操作。

require 'open-uri'
require 'zlib'

stream = open('http://en.wikipedia.org/wiki/France')
if (stream.content_encoding.empty?)
  body = stream.read
else
  body = Zlib::GzipReader.new(stream).read
end

p body

以下是您可以关闭的内容:

>> require 'open-uri' #=> true
>> open('http://en.wikipedia.org/wiki/France').content_encoding #=> ["gzip"]
>> open('http://en.wikipedia.org/wiki/Thailand').content_encoding #=> []

在这种情况下,如果它是[],又名“text/html”,它会读取。如果是它["gzip"],它会解码。

做上面的所有事情并将其扔到:

require 'nokogiri'
page = Nokogiri::HTML(body)
language_part = page.css('div#p-lang')

应该让你回到正轨。

在完成上述所有操作后执行此操作以从视觉上确认您得到了可用的东西:

p language_part.text.gsub("\t", '')

请参阅 Casper 的回答和评论,了解为什么您会看到两个不同的结果。最初看起来 Open-URI 在处理返回的数据时不一致,但根据 Casper 所说的以及我使用 curl 看到的内容,维基百科不尊重大型文档的“Accept-Encoding”标头并返回 gzip。这对于今天的浏览器来说是相当安全的,但是像 Open-URI 这样不能自动感知编码的客户端会有问题。这就是上面的代码应该帮助解决的问题。

于 2011-07-02T20:33:14.710 回答
0
require 'open-uri'
require 'zlib'

open('Accept-Encoding' => 'gzip, deflate') do |response|
  if response.content_encoding.include?('gzip')
    response = Zlib::GzipReader.new(response)
    response.define_singleton_method(:method_missing) do |name|
      to_io.public_send(name)
    end
  end

  yield response if block_given?

  response
end
于 2013-07-08T17:40:58.537 回答
0

After quite a bit of head scratching the problem is here:

> wget -S 'http://en.wikipedia.org/wiki/France'
Resolving en.wikipedia.org... 91.198.174.232
Connecting to en.wikipedia.org|91.198.174.232|:80... connected.
HTTP request sent, awaiting response...
  HTTP/1.0 200 OK
  Content-Language: en
  Last-Modified: Fri, 01 Jul 2011 23:31:36 GMT
  Content-Encoding: gzip <<<<------ BINGO!
  ...

You need to unpack the gzipped data, which open-uri does not do automatically.
Solution:

def http_get(uri)
  url = URI.parse uri

  res = Net::HTTP.start(url.host, url.port) { |h|
    h.get(url.path)
  }

  headers = res.to_hash
  gzipped = headers['content-encoding'] && headers['content-encoding'][0] == "gzip"
  content = gzipped ? Zlib::GzipReader.new(StringIO.new(res.body)).read : res.body

  content
end

And then:

page = Nokogiri::HTML(http_get("http://en.wikipedia.org/wiki/France"))
于 2011-07-02T20:12:31.367 回答