Python 查找Xpath不断变化的元素
我是Python中编写Selenium的新手,我一直试图通过名称、id、xpath找到这个按钮,然后单击它,但没有任何效果 问题是,我找不到按钮,因为xpath不断变化,ID名称只是“button”,这样定位它也不起作用,因为页面上还有很多其他按钮。如何定位该元素 以下是网站的HTML:Python 查找Xpath不断变化的元素,python,selenium,selenium-webdriver,web-scraping,automation,Python,Selenium,Selenium Webdriver,Web Scraping,Automation,我是Python中编写Selenium的新手,我一直试图通过名称、id、xpath找到这个按钮,然后单击它,但没有任何效果 问题是,我找不到按钮,因为xpath不断变化,ID名称只是“button”,这样定位它也不起作用,因为页面上还有很多其他按钮。如何定位该元素 以下是网站的HTML: <ul data-componentname="gender"> <li id="b27296be-e8da-4d5a-acb6-d1674bf88568" class="">
<ul data-componentname="gender">
<li id="b27296be-e8da-4d5a-acb6-d1674bf88568" class="">
<input type="button">
<span>Male</span>
</li>
<li id="32bf7074-6b69-41bb-9869-cf71ac42686f" class="">
<input type="button">
<span>Female</span>
</li>
clickGender = browser.find_element_by_xpath("b27296be-e8da-4d5a-acb6-d1674bf88568")
非常感谢您的帮助。您需要使用:
您的XPATH应该是这样的(假设您想要选择“男性”按钮):
要查找包含“男性”文本的按钮,请使用以下命令:
要查找包含“女性”文本的按钮,请使用以下命令:
根据您共享的HTML,找到与文本相对应的动态按钮,即男性或女性,然后单击该按钮。您必须诱导WebDriverWait以使元素可单击,您可以使用以下解决方案:
- 男:
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@data-componentname='gender']//li//span[contains(.,'Male')]//preceding::input[1]"))).click()
- 女性:
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@data-componentname='gender']//li//span[contains(.,'Female')]//preceding::input[1]"))).click()
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
b27296be-e8da-4d5a-acb6-d1674bf88568
是不断变化的id吗?要单击“男性”按钮吗?请尝试此通过xpath(“//li[contains(,'male')]”)查找元素。
driver.find_element_by_xpath("//li[contains(string(), 'Female')]/input[contains(@type,'button')]")
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@data-componentname='gender']//li//span[contains(.,'Male')]//preceding::input[1]"))).click()
WebDriverWait(browser, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@data-componentname='gender']//li//span[contains(.,'Female')]//preceding::input[1]"))).click()
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC