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

发布于 2021-01-29 14:10:38

我想在默认设置为“季度”的页面上单击“年度”按钮。有两个基本上相同的链接,除了一个链接,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>
关注者
0
被浏览
154
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    我仍然建议您通过 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列表。拥有总是很好explicit wait

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

    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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看