2017-05-08 89 views
0

我有以下格式我試圖用硒/ Python來工作的標記屬性相匹配一個元素:Xpath的:基於相鄰元素

<tr> 
     <td><a href="www.google.com">google</a></td> 
     <td>useless text</td> 
     <td>useless text2</td> 
     <td>useless text3</td> 
     <td><a href="[email protected]">emailaddress</a></td> 
    </tr> 

的想法是,給定一個已知的電子郵件地址(電子郵件地址td中的href的一部分),我可以在第一個td中獲得(並單擊)a。看起來xpath是用Selenium完成這個工作的最佳選擇。我想下面的XPath:

//*[@id="page_content"]/table/tbody/tr[2]/td[2]/div/table[1]/tbody/tr/td[4]/a[contains(@href, "mailto:[email protected]")]/../../td/a[0] 

但我發現了這個錯誤:

selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element: {"method":"xpath","selector":"xpathhere"} 

我知道的XPath來得到了「[email protected]」一個是正確的,因爲它只是從chrome開發工具中複製而來,所以在到達第一個a元素後,錯誤必須與xpath的一部分相關。任何人都可以通過我的xpath瞭解一些問題嗎?

+0

也許只是'// a [包含(@href,「[email protected]」)]'? – splash58

+0

問題是我試圖檢索第一個'td'中的'a',所以我需要找出匹配「[email protected]」'a'後如何返回到那個級別。 – Marcatectura

+0

你應該避免使用索引,總是使用你知道不會改變的東西,比如屬性的一部分,使用索引是一個不好的做法,並不是很靈活。 – lauda

回答

1

首先,請注意(這可能是一個毫無意義的錯字),您正在查找「mailto:[email protected]」,而您的href屬性值爲「[email protected]」。

二,你其實知道如何取回。但Xpath indexing starts with 1。那麼爲什麼這個'a[0]',這也是一個毫無意義的錯字?

無論如何,這個XPath會得到你的兄弟姊妹

'//a[contains(@href, "[email protected]")]/../../td[1]/a[1]' 

或大於使用contains(因爲你可能有其他的電子郵件不會忽略這可以匹配,例如「[email protected]」)

更準確地
'//a[@href="[email protected]"]/../../td[1]/a[1]' 

甚至更​​好,即沒有索引,也沒有父母/孩子喜歡探索。

'//td[a[@href="[email protected]"]]/preceding-sibling::td/a' 

全部測試。

0

嘗試找到包含該電子郵件的tr,然後單擊它的第一個鏈接。

//tr[.//a[contains(@href, 'your_email')]]//a 

​​

//tr[.//a[contains(@href, 'your_email')]]//a[contains(@href, 'common_url_part')] 
0

你的HTML應該是這樣的。

<tr> 
    <td><a href="www.google.com">google</a></td> 
    <td>useless text</td> 
    <td>useless text2</td> 
    <td>useless text3</td> 
    <td><a href="mailto:[email protected]">emailaddress</a></td> 
</tr> 

否則,你的用戶可以點擊鏈接,直到他或她自己的工作陷入狂熱。 :)

然後你可以在硒做這個。

>>> from selenium import webdriver 
>>> driver = webdriver.Chrome() 
>>> driver.get("file://c:/scratch/temp2.htm") 
>>> link = driver.find_element_by_xpath('.//a[contains(@href,"[email protected]")]') 
>>> link.click() 

我用contains因爲鏈接的電子郵件地址可以是這樣的mailto:Jose Greco <needle.email.com>。PS:順便說一句,我剛剛在我的機器上執行了這個東西。

2

嘗試使用下面的代碼:

from selenium.webdriver.common.by import By 
from selenium.webdriver.support import expected_conditions as EC 
from selenium.webdriver.support.ui import WebDriverWait as wait 

xpath = '//td[a[@href="[email protected]"]]/preceding-sibling::td/a' 
wait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, xpath))).click() 

這應該允許您根據在錶行(tr)的最後一個環節的href屬性匹配第一個鏈接,點擊它,一旦它變成可點擊的

+0

沒有索引,對於意外問題和Selenium最先進的實踐非常有效。 – Kanak