如何在selenium python中使用xpath?

时间:2016-08-29 11:36:53

标签: python selenium xpath

我是Selenium Python的新手。我正在尝试运行以下代码段。它适用于find_element_by_name但不适用于find_element_by_xpath。

知道我做错了吗?

谢谢

from selenium import webdriver
# create a new Firefox session
driver = webdriver.Firefox()
driver.implicitly_wait(10)
driver.maximize_window()
# navigate to the application home page
driver.get("https://www.google.co.uk/")
# get the search textbox

#search_field = driver.find_element_by_xpath("//@name='q'/")  <<<<< NOT Working
search_field = driver.find_element_by_name("q")

search_field.clear()
# enter search keyword and submit
search_field.send_keys("phones")
search_field.submit()

2 个答案:

答案 0 :(得分:1)

试试这个 search_field = driver.find_element_by_xpath(“// input [@ name ='q']”)

答案 1 :(得分:0)

您正在使用

search_field = driver.find_element_by_xpath(&#34; // @ name =&#39; q&#39; /&#34;)

这是xpath的正确语法 xpath的正确语法应该是 - &gt; \\ TAG_NAME [@attribute_name =&#34; ATTRIBUTE_VALUE&#34;]

对于上面的例子它应该是 \输入[@name =&#39; Q&#39;]

尝试这个

search = driver.find_element_by_xpath('//input[@name="q"]')