现在,这是我的 HTML,
<div class = 'div-of-all-names'>
<div class='best-first-name'>
<span itemprop='name'> Alexander </span>
</div>
</div>
我的 Ruby 程序中有这个哈希,
URL = "http://www.xxx.com/xxxxxxxxxxxxxxxx/xxxxxxxxxxx/xxxxxxxx"
agent = Mechanize.new
page = agent.get(URL)
patterns = {1 => ['at("div.div-of-all-names")'],
2 => ['at("div.best-first-name")'] ,
3 => ['search("span[@itemprop='name']")']}
# Selecting those keys that is a number and sorting
p = patterns.keys.select{|i| /[0-9]/ =~ i.to_s }.sort
# p = [1,2,3]
p.each do |i|
p[i].each do |j|
out = page.send(j)
if !(out.blank?)
page = out
p j
break
end
end
end
name = page.inner_text
p name
问题:
<强>1。我不能在 Nokogiri 对象上使用 ruby 的“发送”吗? 因为,我可以使用 ruby 散列并将实际的“search”或“at”与“class”、“id”、“itemprop”或散列中的任何 html 属性一起存储为级别 1、2 和 3。 一旦将它们存储为级别,我将从中检索它们作为“i”或“j”中的循环变量,并在 Nokogiri 对象上使用“.send(j)”。
我试过了,但出现了这个错误,
1.9.3p385 :238 > a
=> "at(\"div.our_price\")"
1.9.3p385 :239 > page.send(a)
NoMethodError: undefined method `at("div.our_price")' for #<Mechanize::Page:0xb2ba6dc>
from (irb):239
<强>2。如果我使用“at”,我只能操作类吗? 比如,
"page.at('span.humble')" **means** <-span-class ='humble'> Humble <-/-span> **then what about** <-span-id='humble'> Humble <-/-span>
最佳答案
需要单独给出方法名和参数发送:
obj.send("methodname", "arg1", "arg2")
关于ruby - 在 Nokogiri 对象上使用 ruby "send"作为 page.send(a) 其中 ="at(' div.class-name')",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15551696/