首页 > 解决方案 > 无法使用 Python 和 Selenium 自动点击

问题描述

我正在尝试自动将需求添加到 TestLink 数据库。我在尝试单击此锚点/跨度时遇到问题。

<a hidefocus="on" class="x-tree-node-anchor" href="javascript:REQ_SPEC_MGMT(17473)" tabindex="1">
<span unselectable="on" id="extdd-6">0:Project-0 (0)</span>
</a>

这是我尝试过的 Python 代码部分:

anchor = browser.find_element_by_xpath('//a[contains(@href, "REQ_SPEC_MGMT")]')
span = anchor.find_element_by_xpath('.//span')

anchor.click()  # Doesn't work
span.click()    # Doesn't work
browser.execute_script("arguments[0].click();", anchor)  # Doesn't work
browser.execute_script("arguments[0].click();", span)    # Doesn't work

我没有收到任何错误,但是当我手动单击链接时仍然没有看到出现的页面。我通过转储属性验证了我找到了正确的锚点/跨度,所以我知道我有正确的元素。我也尝试过长时间的停顿,以确保在我尝试之前该元素是可点击的。关于我做错了什么的任何想法?谢谢!

更新 - 这是 HTML 的较大部分:

<div id="tree_div" style="overflow:auto; height:100%;border:1px solid #c3daf9;" class=" x-panel x-tree">
<div class="x-panel-bwrap" id="ext-gen12"><div class="x-panel-body x-panel-body-noheader" id="ext-gen13" style="overflow: auto;">
<ul class="x-tree-root-ct x-tree-arrows" id="ext-gen14">
<li class="x-tree-node"><div ext:tree-node-id="17472" class="x-tree-node-el x-unselectable x-tree-node-expanded" unselectable="on" id="extdd-1">
<span class="x-tree-node-indent"></span>
<img alt="" src="http://192.168.11.111/third_party/ext-js/images/default/s.gif" class="x-tree-ec-icon x-tree-elbow-end-minus">
<img alt="" src="http://192.168.11.111/third_party/ext-js/images/default/s.gif" class="x-tree-node-icon" unselectable="on" id="extdd-2">
<a hidefocus="on" class="x-tree-node-anchor" href="javascript:TPROJECT_REQ_SPEC_MGMT(17472)" tabindex="1">
<span unselectable="on" id="extdd-3">ProjTasks (0)</span>
</a>
</div>
<ul class="x-tree-node-ct" style="">
<li class="x-tree-node">
<div ext:tree-node-id="17473" class="x-tree-node-el x-unselectable folder x-tree-node-collapsed" unselectable="on" id="extdd-4">
<span class="x-tree-node-indent"><img alt="" src="http://192.168.11.111/third_party/ext-js/images/default/s.gif" class="x-tree-icon"></span>
<img alt="" src="http://192.168.11.111/third_party/ext-js/images/default/s.gif" class="x-tree-ec-icon x-tree-elbow-plus">
<img alt="" src="http://192.168.11.111/third_party/ext-js/images/default/s.gif" class="x-tree-node-icon" unselectable="on" id="extdd-5">
<a hidefocus="on" class="x-tree-node-anchor" href="javascript:REQ_SPEC_MGMT(17473)" tabindex="1">
<span unselectable="on" id="extdd-6">0:Project-0 (0)</span></a></div><ul class="x-tree-node-ct" style="display:none;">
</ul>
</li>

标签: seleniumselenium-webdriverxpathcss-selectorswebdriverwait

解决方案


首先,尝试使用隐式硒等待,以确保所有元素都已下载。

anchor = WebDriverWait(browser,30).until(EC.element_to_be_clickable((By.XPATH, '//a[contains(@href, "REQ_SPEC_MGMT")]')))
span = WebDriverWait(anchor,30).until(EC.element_to_be_clickable((By.XPATH, './/span')))

如果它不能正常工作,请尝试在 href 中执行 js 脚本:

browser.execute_script("javascript:REQ_SPEC_MGMT(17473)") 

或者

browser.execute_script(anchor.get_attribute("href")) 

推荐阅读