我想单击一个按钮,客户详细信息,但出现错误。这是来自python的错误:
Message: no such element: Unable to locate element
我尝试了一些代码(在下面列出),但是没有用。有什么想法吗?
1. driver.find_element_by_xpath("(//a[contains(text(),'Customer Details')])[11]").click()
2. driver.find_element_by_xpath("(//a[@href='https://mylink' and @class=' class="btn-sm bg-navy btn-default"']").click()
3. driver.find_element_by_link_text("Customer Details").click()
这是我的HTML代码:
<table class="table table-bordered table-striped dataTable no-footer DTFC_Cloned" style="width: 100%; padding: 0px; margin: 0px;" role="grid" aria-describedby="tbl_so_info">
<thead>
<tr role="row" style="height: 0px;">
<th class="sorting" tabindex="0" aria-controls="tbl_so" rowspan="1" colspan="1" aria-label=": activate to sort column ascending"></th>
<th class="sorting_desc" tabindex="0" aria-controls="tbl_so" rowspan="1" colspan="1" aria-label="Customer No.: activate to sort column ascending" aria-sort="descending"></th>
</tr>
</thead>
<tbody>
<tr role="row" class="odd" data-dt-row="0" style="height: 38px;">
<td data-dt-row="0" data-dt-column="0">
<a href="https://mylink" onclick="window.open('https://mylink', '_blank'); return false;" class="btn-sm bg-navy btn-default" align="center">Customer Details</a>
<a href="https://my_second_link" onclick="window.open('https://my_second_link', '_blank'); return false;" class="btn-sm bg-navy btn-default" align="center">Create Ticket</a>
</td>
</tr>
</tbody>
</table>
使用WebDriverWait
等待元素可单击,然后再单击它:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
# ...
wait = WebDriverWait(driver, 10)
wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Customer Details'))).click()
# css selector
# wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[href="https://mylink"]'))).click()
直到您添加[11]为止,您编写的xpath都是正确的。现在,您的代码正在使用客户详细信息搜索标签。但是添加[11]将导致它在该元素中搜索代码中不存在的第11个结果。因此,它说没有找到这样的元素。
尝试仅编写以下代码,它将正常工作。
xpath =“ // a [包含(text(),'客户详细信息')]”
NOTE:- 从不使用定位器中的这些([1] [11] [2])内容不是一个好方法,因为程序的结构发生了变化,那么定位器可能不会工作。
对于元素上的click()
,您需要为element_to_be_clickable()
引入WebDriverWait,并且可以使用以下任何一个Locator Strategies:
使用LINK_TEXT
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.LINK_TEXT, "Customer Details"))).click()
使用CSS_SELECTOR
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.btn-sm.bg-navy.btn-default[href='https://mylink']"))).click()
使用XPATH
:
WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[@class='btn-sm bg-navy btn-default' and @href='https://mylink'][contains(.,'Customer Details')]"))).click()
Note:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
您可以在以下位置找到相关的详细讨论: