python - 如何使用 Selenium 从非选择下拉菜单中单击一个项目

标签 python selenium-webdriver iframe drop-down-menu webdriverwait

尝试选择其他财务报表(默认为损益表),以及在年度/季度第二个列表之间切换。我可以缩小范围以获取列表的属性,但我无法与列表交互。

import time
import urllib.request
from bs4 import BeautifulSoup
from selenium import webdriver

symbol = 'bmo'
driver = webdriver.Chrome()
driver.get('https://web.tmxmoney.com/financials.php?qm_symbol={}'.format(symbol))
time.sleep(2)
dropdown = driver.find_elements_by_css_selector('a.qmod-dropdown_toggle.qmod-type-toggle + ul.qmod-dropdown-menu > li > a')

for option in dropdown:
    if option.get_attribute('innerText') == 'Balance Sheet':
        option.send_keys('Balance Sheet')

最佳答案

选择 文本为 Assets 负债表的选项,您必须为element_to_be_clickable()引发WebDriverWait,并且您可以使用以下Locator Strategies :

  • xpath:

    from selenium import webdriver
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.support import expected_conditions as EC
    
    driver.get('https://web.tmxmoney.com/financials.php?qm_symbol=bmo')
    element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//h4[text()='Financials for Bank of Montreal']")))
    driver.execute_script("window.scrollBy(0,600)")
    ActionChains(driver).move_to_element(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//a[@class='qmod-dropdown_toggle qmod-type-toggle']/span[text()='Income Statement']")))).perform()
    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='qmod-dropdown-menu']//li/a[text()='Balance Sheet']"))).click()
    

关于python - 如何使用 Selenium 从非选择下拉菜单中单击一个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60403436/

相关文章:

java - 单击 List<WebElement> 中找到的所有元素

HTML -- iframe 的高度占宽度的百分比

python - Subprocess.popen() 不能在 Windows 上的参数中使用引号

python - cached_property 何时重置?

Python Selenium 使用 PhantomJS webdriver 禁用 CSS

java - Selenium WebDriver 选择组合框项目?

python - 图中轴矢量场的缩放颤动图

python - 按范围排列列表

html - Iframe 未显示在 Drupal 站点中

javascript - 设置 iframe 的样式,然后使其可见