問題描述
我想在默認設置為季度"的頁面上單擊年度"按鈕.有兩個鏈接基本上被稱為相同,除了一個有 data-ptype="Annual"
所以我嘗試復制 xpath 以單擊按鈕(也嘗試了其他選項,但沒有一個有效).
I'd like to click the button 'Annual' at a page that is by default set on 'Quarterly'. There are two links that are basically called the same, except that one has data-ptype="Annual"
so I tryed to copy the xpath to click the button (also tried other options but none did work).
但是,我得到 AttributeError: 'list' object has no attribute 'click'
.我閱讀了很多類似的帖子,但無法解決我的問題..所以我認為 javascript 事件必須以某種方式被調用/單擊/執行.. idk 我卡住了
However, I get the AttributeError: 'list' object has no attribute 'click'
. I read a lot of similar posts, but wasn't able to fix my problem.. so I assume that javascript event must be called/clicked/performed somehow differnt.. idk Im stuck
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>
推薦答案
我仍然建議你使用 linkText 而不是 XPATH.這個 xpath 的原因: /html/body/div[5]/section/div[8]/div[1]/a[1]
非常絕對,如果有 可能會失敗又一個 div 添加或從 HTML 中刪除.而更改鏈接文本的機會非常小.
I would still suggest you to go with linkText over XPATH. Reason this xpath : /html/body/div[5]/section/div[8]/div[1]/a[1]
is quite absolute and can be failed if there is one more div added or removed from HTML. Whereas chances of changing the link Text is very minimal.
所以,而不是這個代碼:
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 元素,將 find_elements
用于 Web 元素列表.顯式等待
總是好的.
and yes @Druta is right, use find_element
for one web element and find_elements
for list of web element. and it is always good to have explicit wait
.
像這樣創建顯式等待的實例:
Create instance of explicit wait like this :
wait = WebDriverWait(driver,20)
并像這樣使用等待引用:
and use the wait reference like this :
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
這篇關于AttributeError: 'list' 對象沒有使用 Selenium 和 Python 的屬性 'click'的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!