英文:
Unable to locate and click on li element within ul list
问题
我正在尝试点击一个 ul 下拉列表中的 li 元素。我想选择“上个月”,但出现了以下错误:消息:没有这样的元素:无法找到元素。
以下是我的代码:
def click_on(xpath):
timeout = time.time() + 30
while True:
try:
driver.find_element(By.XPATH, xpath).click()
break
except Exception:
if time.time() > timeout:
msgbox('30 秒后进程超时。', '错误')
exit()
click_on('//*[id="popover_otrppv916b"]/div/div[2]/div[1]/div/div/div/div/ul/li[9]/div/span')
这里是HTML代码:
我还尝试过点击 <div>
标签和 <li>
标签(而不是 <span>
标签),但出现了相同的错误。
英文:
I'm trying to click on an li element in a ul dropdown list. I want to select "Last Month" but get this error: Message: no such element: Unable to locate element
Here's my code:
def click_on(xpath):
timeout = time.time() + 30
while True:
try:
driver.find_element(By.XPATH, xpath).click()
break
except Exception:
if time.time() > timeout:
msgbox('Process timed out after 30 seconds.', 'Error')
exit()
click_on('//*[@id="popover_otrppv916b"]/div/div[2]/div[1]/div/div/div/div/ul/li[9]/div/span')
Here's the html:
I've also tried clicking on just the <div>
tag, and just the <li>
tag (instead of the <span>
tag) and I get the same error.
答案1
得分: 0
_id_属性值,如popover_otrppv916b
,是动态生成的,并且可能会在不久的将来更改。它们可能会在下次访问应用程序时或者在下次启动应用程序时发生变化,因此不能用作定位元素的依据。
解决方案
要单击具有文本"上个月"的可单击元素,您需要使用WebDriverWait来等待元素变为可单击状态,然后您可以使用以下任一定位策略:
- 使用XPATH和
normalizespace()
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='group-list']//li//span[normalizespace()='上个月']"))).click()
- 使用XPATH和
contains()
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='group-list']//li//span[contains(., '上个月')]"))).click()
- 注意:您需要添加以下导入语句:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
请注意,上述代码示例中的文本"上个月"是中文翻译,如果需要英文版本的代码,请提供英文文本。
英文:
The id attribute values like popover_otrppv916b
are dynamically generated and is bound to change sooner/later. They may change next time you access the application afresh or even while next application startup. So can't be used in locators.
Solution
To click on the clickable element with text as Last month you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following locator strategies:
-
Using XPATH and
normalizespace()
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='group-list']//li//span[normalizespace()='Last month']"))).click()
-
Using XPATH and
contains()
:WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='group-list']//li//span[contains(., 'Last month')]"))).click()
-
Note: You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论