为什么网页元素的点击功能不起作用(使用Python的Selenium模块)?

2024-09-30 14:31:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试自动化一项可以为我节省数千次点击的任务

我在Python中搜索了一些可用的模块,并选择使用Selenium

我安装了Firefox驱动程序并取得了一些进展,但我被困了很长时间。我最终放弃了,开了一个堆栈溢出帐户,想把这个问题带到这个有用的介质中

我的代码可以成功地执行一些单击操作,但我无法让代码单击类似按钮的元素。我必须单击这些项目,以便页面打开一些新元素。(希望我将单击这些新元素以自动保存一些excels文件)

以下是按预期工作的部分:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time

browser = webdriver.Firefox()
url =  "https://www.tbb.org.tr/tr/bankacilik/banka-ve-sektor-bilgileri/istatistiki-raporlar/59"
browser.get(url)
time.sleep(2)

bank_reports_element_xpath = "//*[@title=  'Tüm Raporlar']"
bank_reports_element = browser.find_element_by_xpath(bank_reports_element_xpath)
bank_reports_element.click()
time.sleep(2)

second_item = "//div[@data-catid = '52']"
finance_tables_element = browser.find_element_by_xpath(second_item)
finance_tables_element.click()

years_item = "//div[@class = 'years']"
years_element = finance_tables_element.find_element_by_xpath(years_item)
year_elements = years_element.find_elements_by_xpath("a")

在那里,我想点击这些年。 a screenshot of the years that I can't click using Selenium

例如,我得到了与2004年相关的元素

year2004 = year_elements[2]

发出year2004.click()命令将产生ElementNotInteractiableException异常

year2004.click()  # ElementNotInteractableException: Element could not be scrolled into view

在搜索类似帖子的基础上,我尝试了以下方法(通过javascript执行单击)。我没有出错,但它没有任何作用。当我用鼠标点击year2004按钮时,页面中会弹出一个列表。但是当我运行下面的代码时,页面中不会弹出列表

browser.implicitly_wait(4)
browser.execute_script("arguments[0].scrollIntoView();", year2004)
browser.execute_script("arguments[0].click()", year2004)

我还尝试了以下代码。我得到“TypeError:rect未定义”

browser.implicitly_wait(4)
action = ActionChains(browser)
action.move_to_element(year2004)       # gives: TypeError: rect is undefined
action.click(on_element = year2004)    # gives: TypeError: rect is undefined
action.perform()

我尝试使用Chrome驱动程序,得到了类似的结果。错误定义不完全相同。与上面的“rect is undefined”错误不同,Chrome错误类似:“Javascript错误:未能在“Document”上执行'elementsFromPoints':提供的双精度值是非有限的”

我不知道它是否相关,但year2004.location字典的“x”值为0

如果你能回答我,我将不胜感激

保持安全


Tags: 代码rectbrowserby错误actionelementfind
1条回答
网友
1楼 · 发布于 2024-09-30 14:31:47

使用此xpath将为您提供52个类别中的所有元素

//div[@data-catid='52']/descendant-or-self::*/div[@class='years']/child::a

要滚动,请尝试

browser.send_keys(Keys.PAGE_DOWN)

我手动检查,向下翻页按钮对我有效,按两次按钮可获得所需元素

相关问题 更多 >