當使用顯式文本時,它可以作業并且找到的元素被點擊,但當我使用變數時沒有:
這是 div:<div unselectable="on" > 68915969-LS </div>
這有效:
result = driver.find_element(By.XPATH,"//div[contains(text(),'68915969-LS')]")
action = ActionChains(driver)
action.move_to_element(result).click().perform()
當我用變數替換“68915969-LS”時,什么也沒有發生(沒有錯誤,沒有點擊找到的行):
doc_number = '68915969-LS'
result = driver.find_element(By.XPATH,"//div[contains(text(),doc_number)]")
action = ActionChains(driver)
action.move_to_element(result).click().perform()
知道為什么嗎?
干杯丹尼爾
uj5u.com熱心網友回復:
您實際上是在尋找“doc_number”作為字串。您需要決議您的值并將其加入您的 xpath 字串中。
嘗試這個:
driver.find_element(By.XPATH,"//div[contains(text(),'" doc_number "')]")
uj5u.com熱心網友回復:
driver.find_element(By.XPATH,f"//div[contains(text(),'{doc_number}')]")
如果你愿意,你也可以 f 字串并將你的變數放入。
uj5u.com熱心網友回復:
非常感謝。你完全正確。不知何故,我為 xpath 只是一個字串而苦苦掙扎......我使用了這個,它作業得很好:
result=driver.find_element(By.XPATH,"//div[contains(text(),'%s')]"% str(doc_number))
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/495865.html
