MySQL 列 ( product_path
) 具有值//*[(@id=\"scroller\")]/li/*/a
。将它与 Nokogiri 一起使用会抛出Nokogiri::XML::XPath::SyntaxError: Invalid expression:
什么问题。
require 'mysql2'
require 'active_record'
ActiveRecord::Base.establish_connection(
:adapter => "mysql2",
:host => "localhost",
...
)
class MyTable < ActiveRecord::Base
end
@s = MyTable.first
#...Looks like backward slash is escaped automatically by mysql
@s.product_path #=> "//*[(@id=\\\"scroller\\\")]/li/*/a"
p = Nokogiri::HTML(open(@s.url))
#all variations below throw invalid expression error
p.search(@s.product_path).count
p.search("#{@s.product_path").count
p.xpath(@s.product_path).count
#But this works flawlessly.
p.search("//*[(@id=\"scroller\")]/li/*/a").count #=> works fine.
更新
我试过了,它奏效了。
a = '//*[(@id="scroller")]/li/*/a'
p.search(a).count
额外的反斜杠似乎造成了问题。我该如何摆脱它们?