如何使用Selenium从具有特殊设置的网站(Python)的下拉列表中选择值

如何使用Selenium从具有特殊设置的网站(Python)的下拉列表中选择值,python,selenium,automation,Python,Selenium,Automation,注意:我特别处理这个问题 如何将selenium与Python结合使用,使评论按“最近”排序 我尝试的是: driver.find_element_by_id('sort-order-dropdown').send_keys('Most recent') 从没有导致任何错误,但不起作用 然后我试着 from selenium.webdriver.support.ui import Select select = Select(driver.find_element_by_id('sort-

注意:我特别处理这个问题

如何将selenium与Python结合使用,使评论按“最近”排序

我尝试的是:

driver.find_element_by_id('sort-order-dropdown').send_keys('Most recent') 
从没有导致任何错误,但不起作用

然后我试着

from selenium.webdriver.support.ui import Select

select = Select(driver.find_element_by_id('sort-order-dropdown'))
select.select_by_value('recent')
select.select_by_visible_text('Most recent')
select.select_by_index(1)
我得到:
消息:元素在点(66.18333435058594843.7999877929688)处不可单击,因为另一个元素使其模糊

这个

element = driver.find_element_by_id('sort-order-dropdown')
element.click()
li = driver.find_elements_by_css_selector('#sort-order-dropdown > option:nth-child(2)')
li.click()
从导致了相同的错误消息

这一次也导致了同样的错误

Select(driver.find_element_by_id('sort-order-dropdown')).select_by_value('recent').click()
因此,我很想知道是否有任何方法可以从最新的第一篇评论中选择要排序的评论


谢谢

这对我使用Java很有效:

@Test
public void amazonTest() throws InterruptedException {
    String URL = "https://www.amazon.com/Harry-Potter-Slytherin-Wall-Banner/product-reviews/B01GVT5KR6/ref=cm_cr_dp_d_show_all_top?ie=UTF8&reviewerType=all_reviews";
    String menuSelector = ".a-dropdown-prompt";
    String menuItemSelector = ".a-dropdown-common .a-dropdown-item";

    driver.get(URL);

    Thread.sleep(2000);

    WebElement menu = driver.findElement(By.cssSelector(menuSelector));
    menu.click();

    List<WebElement> menuItem = driver.findElements(By.cssSelector(menuItemSelector));
    menuItem.get(1).click();
}

请记住,css选择器是xpath的更好选择,因为它们更快、更健壮、更易于阅读和更改。

这是我从最近的评论中整理评论的简化版本。正如上面“Eugene S”所说,关键点是点击按钮本身,然后从列表中选择/点击所需的项目。但是,我的Python代码使用XPath而不是选择器

# click on "Top rated" button
driver.find_element_by_xpath('//*[@id="a-autoid-4-announce"]').click() 
# this one select the "Most recent"
driver.find_element_by_xpath('//*[@id="sort-order-dropdown_1"]').click() 

你的第一个链接是brokenMy抱歉。已经修好了。我不知道你指的是什么下拉菜单。对我来说,为了进入下拉菜单,我必须首先选择“查看所有71条客户评论。是这样的还是我遗漏了什么?可能是@Eugene S的重复是的,我想从那个页面排序。很抱歉给你带来了困惑。也更新了帖子。谢谢你的补充评论。谢谢你。试图将您的代码翻译成Python,但到目前为止运气不佳。谢谢您的光临。@bensw我添加了一个Python版本。请记住,css选择器是xpath更好的替代品,因为它们更快、更健壮、更易于阅读和更改。@Eugene S,这很有效。我会接受你的回答为正确答案。
# click on "Top rated" button
driver.find_element_by_xpath('//*[@id="a-autoid-4-announce"]').click() 
# this one select the "Most recent"
driver.find_element_by_xpath('//*[@id="sort-order-dropdown_1"]').click()