无法使用python和selenium找到xpath为的元素
您好,我正在尝试访问selenium中的一个元素,当我检查元素时,它看起来像这样:无法使用python和selenium找到xpath为的元素,python,selenium-webdriver,xpath,css-selectors,webdriverwait,Python,Selenium Webdriver,Xpath,Css Selectors,Webdriverwait,您好,我正在尝试访问selenium中的一个元素,当我检查元素时,它看起来像这样: <div class="im_message_outer_wrap hasselect" ng-click="toggleMessage(historyMessage.mid, $event)" data-msg-id="5973"> 这会不断返回一个错误,表示无法定位元素。我做错了什么,或者是否有更好的方法访问此元素。数据msg ID很重
<div class="im_message_outer_wrap hasselect" ng-click="toggleMessage(historyMessage.mid, $event)" data-msg-id="5973">
这会不断返回一个错误,表示无法定位元素。我做错了什么,或者是否有更好的方法访问此元素。数据msg ID很重要,因为在代码中,我希望能够遍历ID以按顺序获取每个元素。要定位元素,可以使用以下任一方法:
- 使用
:css\u选择器
element = driver.find_element(By.CSS_SELECTOR, "div.im_message_outer_wrap.hasselect[ng-click^='toggleMessage']")
- 使用
:xpath
element = driver.find_element(By.XPATH, "//div[@class='im_message_outer_wrap hasselect' and starts-with(@ng-click, 'toggleMessage')]")
理想情况下,要定位可点击的元素,您需要将
元素归纳为可点击的()
,您可以使用以下任一选项:
- 使用
:CSS\u选择器
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div.im_message_outer_wrap.hasselect[ng-click^='toggleMessage']")))
- 使用
:XPATH
element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//div[@class='im_message_outer_wrap hasselect' and starts-with(@ng-click, 'toggleMessage')]")))
- 注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC