簡體   English   中英

如何使用 python 從 selenium 的下拉列表中 select 項目?

[英]How do I select an item from dropdown in selenium using python?

在此處輸入圖像描述

我正在嘗試從下拉菜單中選擇 select 'Newest'。

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
options = webdriver.ChromeOptions()
# options.add_argument('--headless')
driver = webdriver.Chrome(chrome_options=options)

url = 'https://play.google.com/store/apps/details?id=com.whatsapp&hl=en&showAllReviews=true'
driver.get(url)

state_selection = driver.find_element_by_xpath("//div[.='%s']" % "Most relevant")
state_selection.click()
state_selection.send_keys(Keys.UP)
state_selection.send_keys(Keys.UP)
state_selection2 = driver.find_element_by_xpath("//div[.='%s']" % "Newest")
state_selection2.send_keys(Keys.RETURN)

但是一旦它到達最新並且我發送命令按回車(如代碼所示),它就會重置為“最相關”。 我無法弄清楚如何實現這一目標。

單擊 state_selection 后,類似這樣的內容將單擊“最新”:

driver.find_element_by_xpath("//div[@role='option']/span[contains(text(),'Newest')]").click()

更強大的方法是使用WebdriverWait以允許 DOM 更新,因此:

WebDriverWait(driver,5).until(EC.visibility_of_element_located((By.XPATH, "//div[@role='option']/span[contains(text(),'Newest')]"))).click()

請注意,您需要這些導入WebdriverWait

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait

有不同的方法可以找到

  • 指數
  • 價值
  • 可見文本

當您使用 xpath 時,如果將來更改值,它只會選擇該位置中存在的元素。因此,通過可見文本對用戶 select 更好

state_selection=Select(driver.find_element_by_xpath("//div[.='%s']" % "Most relevant").click();
state_selection.select_by_visible_text("Dropdown Visible Text")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM