如何使用python从硒的下拉列表中选择一个项目?

时间:2020-05-19 12:38:12

标签: python selenium

enter image description here

我正在尝试从下拉菜单中选择“最新”。

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)

,但是一旦到达最新,并且我发送命令按Enter(如代码所示),它就会重置为“最安全”。我无法全力以赴地实现这一目标。

2 个答案:

答案 0 :(得分:1)

单击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

答案 1 :(得分:0)

有多种查找方法

  • 索引
  • 可见文字

如果以后更改值时使用xpath时,它将仅选择该位置中存在的元素。因此,最好由可见文本用户选择

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