简体   繁体   中英

Selenium element cannot be found drop down menu python

I am using Selenium WebDriver on the eBay website. I am trying to change the drop down menu from best match to lowest price + P&P. This is my code:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
sortdown = browser.find_element(By.XPATH, '//*[@id="DashSortByContainer"]/ul[1]/li/div/a')
sortselect = Select(sortdown)
sortselect.select_by_visible_text('Lowest price + P&P')

I have used XPATH in case the element is dynamic. And python still says the element cannot be found. Can anyone help? Here is an example link with the drop down menu at the top right of the results: https://www.ebay.co.uk/sch/i.html?_from=R40&_trksid=m570.l1313&_nkw=harley&_sacat=0

The items it displays are not real Select elements. It's just a <ul with bunch of links, hidden by default. So I would suggest something like this:

  1. Select current sort link ( <a ) to open list of other options. Easiest to do so is by link text. Selectors like ul[1]/li/div/ are just confusing and unnecessary. Note that depending on what precedes this operation, you may also need this link to show up.
  2. Select new option once it shows up (ie wait for it, then click).

Eg:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

wait = WebDriverWait(browser, 10)

# click link to display all options
sortdown = browser.find_element_by_link_text('Best Match')
sortdown.click()

# select a new option
lowestprice = wait.until(EC.presence_of_element_located((By.LINK_TEXT, 'Lowest price + P&P')))
lowestprice.click()

The element //*[@id="DashSortByContainer"]/ul[1]/li/div/a is a link, not select. That's why you cannot use Select class.
You need click on the //*[@id="DashSortByContainer"]/ul[1]/li/div/a , then locate you elements with values in the DOM and click one you need.

You can find similar question here with answer you can use as a reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM