[英]How do I select an item from dropdown in selenium using python?
I'm trying to select 'Newest' from the drop-down menu.我正在尝试从下拉菜单中选择 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)
but as soon as it reaches Newest and as I send command to press enter(as shown in code),it resets to "Most Relevent".但是一旦它到达最新并且我发送命令按回车(如代码所示),它就会重置为“最相关”。 I'm not able to get my head around on how to achieve this.我无法弄清楚如何实现这一目标。
After you have clicked state_selection, something like this will click "Newest":单击 state_selection 后,类似这样的内容将单击“最新”:
driver.find_element_by_xpath("//div[@role='option']/span[contains(text(),'Newest')]").click()
The more robust method would be working with WebdriverWait
to allow the DOM to update, so:更强大的方法是使用WebdriverWait
以允许 DOM 更新,因此:
WebDriverWait(driver,5).until(EC.visibility_of_element_located((By.XPATH, "//div[@role='option']/span[contains(text(),'Newest')]"))).click()
Note you need these imports for WebdriverWait
:请注意,您需要这些导入WebdriverWait
:
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
There are different ways to find有不同的方法可以找到
When you use the xpath if the values are changed in future,it pick that element present in that location only.So its better to user select by visible text当您使用 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.