长话短说:
无论出于何种原因,我的 selenium python 脚本似乎无法“点击”我需要的按钮。
上下文:
你好。我的任务可能是很多人都熟悉的:我想将打开网站、登录和单击网站内的几个下拉菜单链接的过程自动化,这最终会引导我进入一个页面,我可以在其中可以下载电子表格。我可以打开网页并登录。要继续,我必须:
- 单击下拉菜单标题,然后
- 在下拉菜单中,点击相应的选项。
这是网站上相关 HTML 代码的快照:
<td class="x-toolbar-cell" id="ext-gen45">
<table id="ext-comp-1045" class="x-btn x-btn-noicon" style="width: auto;" cellspacing="0">
<tbody class="x-btn-small x-btn-icon-small-left">
<tr>
<td class="x-btn-ml"><i> </i></td>
<td class="x-btn-mc">
<em class="x-btn-arrow" unselectable="on">
<button type="button" id="ext-gen46" class=" x-btn-text">Reports</button>
</em>
</td>
<td class="x-btn-mr"><i> </i></td>
</tr>
</tbody>
</table>
</td>
我需要“点击”的项目有一个button
标签,具体来说:
<button type="button" id="ext-gen46" class=" x-btn-text">Reports</button>
要用 selenium 选择它,我尝试了以下方法:
reports_click_element = browser.find_element_by_id('ext-gen46').click()
当失败时,
reports_element = browser.find_element_by_xpath("//button[contains(text(), 'Reports')]").click()
实际上执行时没有出现 ExceptionMessage 错误,但我发现它选择了页面中具有“报告”文本的其他元素,而不是我需要的特定按钮。
当我试图将需要单击的按钮归零时,解释器返回一条错误消息,指示找不到 html 属性。
我怎样才能从这里开始? (我应该关注我需要点击的按钮正上方元素中的 unselectable="on"
标签吗?)
如果我可以在问题中添加任何内容,请告诉我。提前致谢。
更新: 我已经切换到我认为菜单是其中一部分的 iframe,但我仍然无法选择按钮。到目前为止,这是我的 Python 代码:
from selenium import webdriver
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
import time
binary = FirefoxBinary('C:\Program Files (x86)\Mozilla Firefox\Firefox.exe')
browser = webdriver.Firefox(firefox_binary=binary)
browser.get("https://app.website.com")
login_entry(username, password) # this works fine; it's just a user-created function to login. Ignore.
time.sleep(10) # wait for website's markup to load
browser.switch_to.frame(browser.find_element_by_tag_name("iframe"))
time.sleep(10)
# This is the point where I'm trying to click on the "Reports" button
reports_element = browser.find_element_by_xpath("//*[contains(text(), 'Reports')]") #this refers to other elements
reports_element = browser.find_element_by_xpath("//button[contains(text(), 'Reports')][1]") #no luck here either
最佳答案
我想到了几个案例。
存在多个元素,但并非所有元素都可见
elements = browser.find_elements_by_xpath("//button[contains(text(), 'Reports')]")
for element in elements:
if element.is_displayed():
print "element is visible"
element.click()
else:
print("element is not visible")
print(element)
该元素存在,它应该是可见的但在屏幕之外。
from selenium.webdriver.common.action_chains import ActionChains
elements = browser.find_elements_by_xpath("//button[contains(text(), 'Reports')]")
for element in elements:
ActionChains(driver).move_to_element(element).perform()
try:
element.click()
except:
print("couldn't click on {}".format(element))
您还可以尝试记录您的点击和键盘输入吗 Selenium IDE for Firefox ?然后将其保存为 python 脚本并将其作为评论发布在这里?
关于javascript - Python中的Selenium,无法点击 'button' : Tag not found,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40733868/