我想获得H1文本。该页面从markdown转换为HTML。当我使用下面的代码来使用XPath获取文本时:
element = driver.find_element(xpath: '/html/body/div[3]/div[1]/h1')
element.text
我收到错误:
<driver.find_element(xpath: '/html/body/div[3]/div[1]/h1')
Selenium::WebDriver::Error::NoSuchElementError: no such element: Unable to locate element: {"method":"xpath","selector":"/html/body/div[3]/div[1]/h1"}
(Session info: chrome=62.0.3202.89)
(Driver info: chromedriver=2.33.506120 (e3e53437346286c0bc2d2dc9aa4915ba81d9023f),platform=Windows NT 6.1.7601 SP1 x86_64)
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.6.0/lib/selenium/webdriver/remote/response.rb:71:in `assert_ok'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.6.0/lib/selenium/webdriver/remote/response.rb:34:in `initialize'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.6.0/lib/selenium/webdriver/remote/http/common.rb:83:in `new'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.6.0/lib/selenium/webdriver/remote/http/common.rb:83:in `create_response'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.6.0/lib/selenium/webdriver/remote/http/default.rb:106:in `request'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.6.0/lib/selenium/webdriver/remote/http/common.rb:61:in `call'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.6.0/lib/selenium/webdriver/remote/bridge.rb:170:in `execute'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.6.0/lib/selenium/webdriver/remote/oss/bridge.rb:581:in `execute'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.6.0/lib/selenium/webdriver/remote/oss/bridge.rb:549:in `find_element_by'
from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/selenium-webdriver-3.6.0/lib/selenium/webdriver/common/search_context.rb:62:in `find_element'
from (irb):60
from C:/Ruby23-x64/bin/irb.cmd:19:in `<main>'
请问,有人可以更正此代码或建议另一种获取文本值的方法吗?
感谢。
答案 0 :(得分:0)
当我点击网址时,网站会短暂显示“加载”文字,之后您正在查找的h1文字变为可见。您可以使用隐式等待在超时发生之前等待最长时间。
selenium文档中的示例:
require 'rubygems' # not required for ruby 1.9 or if you installed without gem
require 'selenium-webdriver'
driver = Selenium::WebDriver.for :firefox
driver.manage.timeouts.implicit_wait = 10 # seconds
driver.get "http://somedomain/url_that_delays_loading"
element = driver.find_element(:id => "some-dynamic-element")
此外,由于只有一个h1元素存在,您可以使用更简单的选择器,如css选择器div h1
或xpath选择器//div/h1
原帖
你问题中的两个xpath是不同的:
/html/body/div[3]/footer/nav[2]/ul/li[3]/a
和
/html/body/div[3]/div[1]/h1
你能提供网站HTML吗?