【问题标题】:How do I parse and scrape the meta tags of a URL with Nokogiri?如何使用 Nokogiri 解析和抓取 URL 的元标记?
【发布时间】:2013-07-20 20:41:59
【问题描述】:

我正在使用 Nokogiri 拉取 <h1><title> 标签, 但我无法获得这些:

<meta name="description" content="I design and develop websites and applications.">
<meta name="keywords" content="web designer,web developer">

我有这个代码:

url = 'https://en.wikipedia.org/wiki/Emma_Watson' 
page = Nokogiri::HTML(open(url))

puts page.css('title')[0].text puts page.css('h1')[0].text
puts page.css('description')
puts META DESCRIPTION
puts META KEYWORDS

我查看了文档并没有找到任何东西。我会使用正则表达式来执行此操作吗?

谢谢。

【问题讨论】:

  • 给出完整的html..你的需求不清楚..
  • 澄清一下:Nokogiri 不会爬任何东西。它只做解析。您的代码与 OpenURI 和 Nokogiri 等 gem 一起进行爬取。

标签: ruby html-parsing nokogiri


【解决方案1】:

下面是我的做法:

require 'nokogiri'

doc = Nokogiri::HTML(<<EOT)
<meta name="description" content="I design and develop websites and applications.">
<meta name="keywords" content="web designer,web developer">
EOT

contents = %w[description keywords].map { |name|
  doc.at("meta[name='#{name}']")['content']
}
contents # => ["I design and develop websites and applications.", "web designer,web developer"]

或者:

contents = doc.search("meta[name='description'], meta[name='keywords']").map { |n| 
  n['content'] 
}
contents # => ["I design and develop websites and applications.", "web designer,web developer"]

【讨论】:

    【解决方案2】:

    那就是:

    page.at('meta[name="keywords"]')['content']
    

    【讨论】:

      【解决方案3】:

      另一种解决方案:您可以使用 XPath 或 CSS。

      puts page.xpath('/html/head/meta[@name="description"]/@content').to_s
      puts page.xpath('/html/head/meta[@name="keywords"]/@content').to_s
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-01
        • 1970-01-01
        • 2017-11-09
        • 2013-02-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多