0

enter image description here

I'm trying to select 'Newest' from the drop-down menu.

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.

2
  • Remove the second search for state_selection2 and do state_selection.send_keys(Keys.RETURN). You've already hit up twice Commented May 19, 2020 at 12:41
  • @MadPhysicist if I do so it returns an exception "element not visible" Commented May 19, 2020 at 12:44

2 Answers 2

1

After you have clicked state_selection, something like this will click "Newest":

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(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:

from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
Sign up to request clarification or add additional context in comments.

Comments

0

There are different ways to find

  • Index
  • Value
  • Visible Text

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.