Python - Selenium:如何在网页中单击带有文本"Year"元素


from bs4 import BeautifulSoup as soup
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Font
from selenium import webdriver
from selenium.webdriver.common.by import By
import datetime
import os
import time
import re
browser = webdriver.Chrome(executable_path=r"C:Program Files(x86)GoogleChromeApplicationchromedriver.exe")
my_url = 'https://www.eex.com/en/market-data/power/futures/phelix-at-futures#!/2017/07/24'
browser.get(my_url)
button = browser.find_elements_by_class_name('ng-scope')[-1]
browser.execute_script("arguments[0].click();", button)

它没有给我任何错误,但它实际上并没有点击。它应该逐年变化,因为它是最后一个元素,但它留在那里。

根据您提供的url单击带有文本的元素,如年份,您必须诱导WebDriverWait元素可单击,如下所示:

  • CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "ul.tabs.filter_wrap.clearfix li.ng-scope:nth-child(3)>a"))).click()
    
  • XPATH

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//ul[@class='tabs filter_wrap clearfix']//li[@class='ng-scope']/a[contains(.,'Year')]"))).click()
    

试试这个:

from bs4 import BeautifulSoup as soup
from openpyxl import load_workbook
from openpyxl.styles import PatternFill, Font
from selenium import webdriver
from selenium.webdriver.common.by import By
import datetime
import os
import time
import re
browser = webdriver.Chrome(executable_path=r"C:Program Files(x86)GoogleChromeApplicationchromedriver.exe")
my_url = 'https://www.eex.com/en/market-data/power/futures/phelix-at-futures#!/2017/07/24'
browser.get(my_url)
# wait until button will be present
WebDriverWait(driver, 120).until(EC.presence_of_element_located((By.XPATH, "//*[@id='content']/div/div/ul/li[3]/a")))
# find the button and click on it
button = driver.find_element_by_xpath("//*[@id='content']/div/div/ul/li[3]/a")
button.click()

你可以用不同的方式去皮同一个苹果。但是,在这种情况下,更好的方法是使用不太可能中断的.find_element_by_link_text()。试一试:

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
url = 'https://www.eex.com/en/market-data/power/futures/phelix-at-futures#!/2017/07/24'
driver = webdriver.Chrome()
driver.get(url)
wait = WebDriverWait(driver, 30)
wait.until(EC.presence_of_element_located((By.LINK_TEXT, "Year"))).click()
driver.quit()

相关内容

最新更新