我正在嘗試使用 python selenium 模塊來通過酒精網站“你是 18 歲以上的網頁”檢查。在網站上,我試圖從下拉表中選擇一個區域,我將 python Select 類通過暫存器傳遞,但在 chrome webdriver 中沒有進行任何更改。這是我到目前為止所擁有的,任何建議將不勝感激。網址是:https : //www.shop.liquorland.co.nz/splash.aspx?ReturnUrl=/
from selenium import webdriver
from selenium.webdriver.support.ui import Select
def main(website):
"""This function will be set to work with standard superliquor website format to get store details for the database"""
#load webpage
driver = webdriver.Chrome(executable_path='chromedriver_win32/chromedriver.exe')
driver.get(website)
#accept "I am ages 18 or over" button
acceptage = driver.find_element_by_xpath("/html/body/div[1]/header/div[2]/input[1]").click() #working
#select region, something not working below
regionselect = Select(driver.find_element_by_xpath("/html/body/div[1]/main/form/fieldset/div[1]/select"))#.get_attribute('outerHTML')
regionselect.select_by_index(3) #to test, try selecting Northland
#From here, I expect that the webpage region select would be set to Northlands
#NOTE: Yes I have tried regionselect.select_by_value("3") and select_by_visible_text("Northland")
if __name__ == "__main__":
main('https://www.shop.liquorland.co.nz/splash.aspx?ReturnUrl=/')
uj5u.com熱心網友回復:
不幸的是,有一些自定義選擇/下拉實作(可能是這個),因此您需要手動呼叫下拉,然后單擊所需的選項:
driver.find_element_by_xpath("/html/body/div[1]/main/form/fieldset/div[1]/span").click()
driver.find_element_by_xpath('/html/body//div[contains(@class,"jcf-select-drop-content")]//span[@data-index="2"]').click()
注意:我是如何知道呼叫下拉選單的方法的?當您單擊下拉串列時,您可以看到<span>下面<select>正在更改它的類,因此它應該是這個元素。
uj5u.com熱心網友回復:
當您檢查下拉選單下的選項時,元素位于ul-li標記中而不是Select標記中。
可以選擇所需的選項,如下所示:
# Imports required:
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
driver.get("https://www.shop.liquorland.co.nz/splash.aspx?ReturnUrl=/")
# click on age button
WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,"(//input[@type='button'])[1]"))).click()
# Click on the drop-down
WebDriverWait(driver,30).until(EC.element_to_be_clickable((By.XPATH,"//span[text()='Region']/parent::span"))).click()
# Select option using indexing
# region = driver.find_element_by_tag_name("ul")
# options = region.find_elements_by_tag_name("li")
# options[4].click()
# Select option using specific text
region = driver.find_element_by_tag_name("ul")
option = region.find_element_by_xpath("./li/span[text()='Auckland']")
option.click()
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/350235.html
