如何使用Mechanize填充dom节点输入的值?
我希望该网站能够展示从2010年起生产的一系列卡车,以便我能够解析相关信息。
没有涉及的实际形式。
这是代码:
require "mechanize"
@url = "https://www.kleyntrucks.nl/vrachtwagens/trekker/"
a = Mechanize.new do |agent|
agent.user_agent_alias = 'Mac Safari'
agent.follow_meta_refresh = true
end
a.get(@url) do |page|
bouwjaar_range_field = page.search("#imprp0")
bouwjaar_range_details = bouwjaar_range_field.search(".details")
input = bouwjaar_range_details.search("input")[0]
input.value = "2010"
end
这是输出:
/Users/username/Dropbox/Development/Rails/folder/lib/tasks/experiment.rb:20:in `block in <main>': undefined method `value=' for #<Nokogiri::XML::Element:0x007fd4ab0fd9a8> (NoMethodError)
from /Users/username/.rvm/gems/ruby-2.0.0-p353@global/gems/mechanize-2.7.3/lib/mechanize.rb:442:in `get'
from /Users/username/Dropbox/Development/Rails/folder/lib/tasks/experiment.rb:10:in `<main>'
[Finished in 1.9s with exit code 1]
pp input
给出了以下输出:
#(Element:0x3fe33c82ab68 {
name = "input",
attributes = [
#(Attr:0x3fe33c869430 { name = "type", value = "hidden" }),
#(Attr:0x3fe33c8692a0 { name = "name", value = "slider_from" }),
#(Attr:0x3fe33c869278 { name = "value", value = "1968" })]
})
puts input
给出了以下输出:
<input type="hidden" name="slider_from" value="1968">
有什么想法吗?
更新
我想要它做什么:
答案 0 :(得分:1)
更改第input.value = "2010"
行
到
input['value'] = "2010"
type
,name
等是input
元素的属性。您需要使用Nokogiri::XML::Node#[]=
方法。
将属性 名称 的属性值设置为 值
示例:
require 'nokogiri'
doc = Nokogiri::XML <<-xml
<foo atr = '123'> test </foo>
xml
doc.at('foo')['atr'] # => "123"
doc.at('foo')['atr'] = "999"
puts doc
输出
<?xml version="1.0"?>
<foo atr="999"> test </foo>