2017-02-24 146 views
1

我尝试使用硒的webdriver找到一个元素: i want click the "用户查询"硒的webdriver定位元素

对应的HTML: the red frame

蟒蛇:

>>> driver.find_element_by_xpath("//div[@id='container']/h1[2]/a").click() 
Traceback (most recent call last): 
    File "<pyshell#22>", line 1, in <module> 
    driver.find_element_by_xpath("//div[@id='container']/h1[2]/a").click() 
    File "D:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 293, in find_element_by_xpath 
    return self.find_element(by=By.XPATH, value=xpath) 
    File "D:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 752, in find_element 
    'value': value})['value'] 
    File "D:\Python35\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 236, in execute 
    self.error_handler.check_response(response) 
    File "D:\Python35\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 192, in check_response 
    raise exception_class(message, screen, stacktrace) 
selenium.common.exceptions.NoSuchElementException: Message: no such element 
    (Session info: chrome=52.0.2743.116) 
    (Driver info: chromedriver=2.7.236900,platform=Windows NT 6.1 SP1 x86) 

如何定位这个元素?

回答

0

与索引试试这个下面的XPath。

这里。 [1]表示您的a标签的索引号。假设在你的html中,有一些标签可用不同的名字来表示。 用户查询。假设,这个文本用户查询索引号是你的html里面的一个,然后在xpath下面使用。

//h1[1]/a 

如果本文用户查询指数是两个内线您html然后使用下面的XPath。

//h1[2]/a 
+0

谢谢你你的答案真诚。我尝试它,并改变为“driver.find_element_by_xpath(”// * [text()='用户查询']“)”他们都没有working.any选择? –

+0

当我们从浏览器中看到'html'时,您的文本'用户查询'正在发生变化。我也更新了我的答案。假设你的文本'用户查询'位于html内部,并带有'n(数字)',那么使用xpath作为'// h1 [n]/a' –

+0

是的,我已经尝试过了。在网站上传和切换后,一帧。非常感谢你。 –

0

你可以尝试定位元素based on it's link text

driver.find_element_by_link_text("用户查询").click(); 
+0

感谢您的answer.i尝试,但错误没有这样的element.i认为你是正确的,此元素与文本A HREF,但他们都不是工作,任何想法? –

+0

您能分享整个页面的HTML吗?也许''标签位于'