2017-02-24 143 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嗎?也許''標籤位於'