![](/img/trans.png)
[英]set tag attribute and add plain text content to the tag using nokogiri builder (ruby)
[英]extracting content of content attribute in meta tag of a website given a specified value for the name attribute with nokogiri in ruby?
我在這里的第一個問題是,很難找到答案。 我是新手使用nokogiri。
這是我的問題。 我在目標網站的HTML頭上有這樣的東西(這里是一個techcrunch帖子):
<meta content="During my time at TechCrunch I've seen thousands of startups and written about hundreds of them. I sure as hell don't know all ..." name="description"/>
我現在想要一個腳本來運行元標記,找到名稱屬性為“description”的腳本,並獲取內容屬性中的內容。
我嘗試過這樣的事情
require 'rubygems'
require 'nokogiri'
require 'open-uri'
url = "http://www.techcrunch.com/2009/10/11/the-underutilized-power-of-the-video-demo-to-explain-what-the-hell-you-actually-do/"
doc = Nokogiri::HTML(open(url))
posts = doc.xpath("//meta")
posts.each do |link|
a = link.attributes['name']
b = link.attributes['content']
end
之后我可以選擇屬性名稱等於描述的鏈接 - 但是此代碼對於a和b返回nil。
我玩了posts = doc.xpath("//meta")
, posts = doc.xpath("//meta/*")
等,但仍然沒有。
問題不在於xpath,因為它似乎沒有解析文檔。 您可以使用puts doc
檢查它,它不包含完整輸入。 解析注釋似乎是一個問題(我懷疑無效的HTML或libxml2中的錯誤)。
在您的情況下,我將使用正則表達式作為解決方法 。 鑒於<meta>
標簽足夠簡單可能有效,例如/<meta name="([^"]*)" content="([^"]*)"/
你應該改變
doc = Nokogiri::HTML(open(url))
至
doc = Nokogiri::HTML(open(url).read)
更新:或者可能不是:)實際上你的代碼適用於我,使用ruby 1.8.7 / nokogiri 1.4.0
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.