小编典典

AttributeError:使用Selenium和Python,“列表”对象没有属性“点击”

selenium

我想在默认设置为“季度”的页面上单击“年度”按钮。有两个基本上相同的链接,除了一个链接,data- ptype="Annual"所以我试图复制xpath来单击按钮(也尝试了其他选项,但没有一个起作用)。

但是,我得到了AttributeError: 'list' object has no attribute 'click'。我读了很多类似的文章,但无法解决我的问题..因此,我认为必须调用/单击/执行javascript事件以某种方式不同。

from selenium import webdriver
link = 'https://www.investing.com/equities/apple-computer-inc-balance-sheet'

driver = webdriver.Firefox()
driver.get(link)
elm = driver.find_elements_by_xpath("/html/body/div[5]/section/div[8]/div[1]/a[1]").click()

html如下:

<a class="newBtn toggleButton LightGray" href="javascript:void(0);" data-type="rf-type-button" data-ptype="Annual" data-pid="6408" data-rtype="BAL">..</a>

阅读 531

收藏
2020-06-26

共1个答案

小编典典

我仍然建议您通过 XPATH* 使用 linkText 。原因xpath:是绝对的,如果 从HTML中 添加
删除了 另一个div ,则可能会失败。而更改链接文本的机会非常小。
/html/body/div[5]/section/div[8]/div[1]/a[1] *****

因此,代替此 代码

elm = driver.find_elements_by_xpath("/html/body/div[5]/section/div[8]/div[1]/a[1]").click()

试试这个代码:

annual_link = driver.find_element_by_link_text('Annual')
annual_link.click()

是的@Druta是正确的,find_element用于一个Web元素和Web元素find_elements列表。拥有总是很好explicitwait

创建显式等待的实例,如下所示:

wait = WebDriverWait(driver,20)

并使用如下的等待引用:

wait.until(EC.elementToBeClickable(By.LINK_TEXT, 'Annual'))

更新:

from selenium import webdriver
link = 'https://www.investing.com/equities/apple-computer-inc-balance-sheet'

driver = webdriver.Firefox()
driver.maximize_window()
wait = WebDriverWait(driver,40)
driver.get(link)

driver.execute_script("window.scrollTo(0, 200)")

wait.until(EC.element_to_be_clickable((By.LINK_TEXT, 'Annual')))
annual_link = driver.find_element_by_link_text('Annual')
annual_link.click()
print(annual_link.text)

确保导入这些:

from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
2020-06-26