简体   繁体   中英

using variable in xpath on ruby with nokogiri

require 'nokogiri'
require 'open-uri'

1.upto(10) do |x|
url = TOPSECRET
page = Nokogiri::HTML(open(url))

title = page.xpath('//span[@class="tit"][#{x}]').inner_html

puts "#{x}, #{title}"
end

the error occurs [#{x}] <= here

how can I fix this?

The problem is with your use of single quotes instead of double quotes.

change this:

title = page.xpath('//span[@class="tit"][#{x}]').inner_html

to this:

title = page.xpath("//span[@class=\"tit\"][#{x}]").inner_html

for proper variable expansion. Note also the escaping of internal double quotes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM