如何跳至下一页?

问题描述 投票:0回答:1

我只是想抓取一个网站,但被卡住了。这是我的代码:

from selenium import webdriver

driver = webdriver.Firefox(executable_path='location of the geckodriver')
driver.get('http://kernyilvantartas.zalajaras.hu/public/')
driver.find_element_by_xpath("""//*[@id="btn"]""").click()
# the dropdown menu
driver.find_element_by_xpath("""//*[@id="lap"]""").click()
# click on page 2
driver.find_element_by_xpath("""//*[@id="lap"]/option[2]""").click()

在click()之后,它仅突出显示下拉菜单上的第二个选项,但不跳到下一页。有什么主意吗?

python-3.x selenium xpath css-selectors webdriverwait
1个回答
0
投票

您要交互的元素是<select>节点,因此您需要使用Select类,并且可以使用以下Locator Strategies中的任何一个:

  • 使用CSS_SELECTORselect_by_value()方法:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.select import Select
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get('http://kernyilvantartas.zalajaras.hu/public/')
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input#btn"))).click()
    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "select[name='lap']"))))
    select.select_by_value("2")
    
  • 使用XPATHselect_by_visible_text()方法:

    from selenium import webdriver
    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    from selenium.webdriver.support.select import Select
    
    options = webdriver.ChromeOptions() 
    options.add_argument("start-maximized")
    options.add_experimental_option("excludeSwitches", ["enable-automation"])
    options.add_experimental_option('useAutomationExtension', False)
    driver = webdriver.Chrome(options=options, executable_path=r'C:\Utility\BrowserDrivers\chromedriver.exe')
    driver.get('http://kernyilvantartas.zalajaras.hu/public/')
    WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//input[@id='btn']"))).click()
    select = Select(WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.XPATH, "//select[@name='lap']"))))
    select.select_by_visible_text("2")
    
© www.soinside.com 2019 - 2024. All rights reserved.