Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/xpath/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何打印XPath值?_Ruby_Xpath_Mechanize - Fatal编程技术网

Ruby 如何打印XPath值?

Ruby 如何打印XPath值?,ruby,xpath,mechanize,Ruby,Xpath,Mechanize,我想打印XPath节点的内容。以下是我所拥有的: require "mechanize" agent = Mechanize.new agent.get("http://store.steampowered.com/promotion/snowglobefaq") puts agent.xpath("//*[@id='item_52b3985a70d58']/div[4]") 这将返回::未定义的方法xpath for#(NoMethodError) 我刚开始使用Mechanize,不知道我在

我想打印XPath节点的内容。以下是我所拥有的:

require "mechanize"
agent = Mechanize.new
agent.get("http://store.steampowered.com/promotion/snowglobefaq")
puts agent.xpath("//*[@id='item_52b3985a70d58']/div[4]")
这将返回:
:未定义的方法xpath for#(NoMethodError)


我刚开始使用Mechanize,不知道我在做什么,但是,我使用了Watir,并认为这会起作用,但它没有起作用。

您可以在检索页面后使用Nokogiri解析页面。下面是示例代码:

m = Mechanize.new
result = m.get("http://google.com")

html = Nokogiri::HTML(result.body)
divs = html.xpath('//div').map { |div| div.content } # here you can do whatever is needed with the divs
                                                     # I've mapped their content into an array

有两件事不对:

  • 该页上不存在该ID。尝试此操作以查看可用的标记ID列表:

    require "open-uri"
    require 'nokogiri'
    
    doc = Nokogiri::HTML(open("http://store.steampowered.com/promotion/snowglobefaq"))
    puts doc.search('[id*="item"]').map{ |n| n['id'] }.sort
    
  • 正确的方法链是
    agent.page.xpath

  • 因为没有示例HTML显示您想要的标签,所以我们无法为您提供太多帮助。

    它没有打印任何内容,但也没有给出任何错误。现在只是想弄清楚xpath出了什么问题吗?你想做什么?我只是想把文本打印到xpath中。我认为XPath是一种简单的方法,因为我不知道如何使用HTML指定我想要的东西。XPath对应于此图中的第一个“X,XXX”数字:我在答案中编写了示例代码。我希望它能帮助你。对不起,我得走了。我明天登记。你可以像这样使用它:
    agent.page.at(“//*[@id='item\u 52b3985a70d58']/div[4]”