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

2024-04-26 10:04:56 发布

您现在位置:Python中文网/ 问答频道 /正文

注意:我特别处理这个website

如何将selenium与Python一起使用以获得对this page的评论,并按“最近”排序?在

我尝试的是:

driver.find_element_by_id('sort-order-dropdown').send_keys('Most recent') 

来自this没有引起任何错误,但不起作用。在

然后我试过了

^{pr2}$

我有:Message: Element <select id="sort-order-dropdown" class="a-native-dropdown" name=""> is not clickable at point (66.18333435058594,843.7999877929688) because another element <span class="a-dropdown-prompt"> obscures it

这个

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

this引起相同的错误消息

来自this的这个也导致了相同的错误

Select(driver.find_element_by_id('sort-order-dropdown')).select_by_value('recent').click()

所以,我很想知道有没有什么方法可以让我从最近的第一篇评论中挑选出来。在

谢谢你


Tags: idbydriver错误评论orderelementfind
2条回答

这是我从最近的评论中整理出来的简化版。正如上面“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() 

这对我使用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();
}

可以重用元素名称,并使用Python遵循类似的路径。在

这里的要点是:

  1. 单击菜单本身
  2. 单击第二个菜单项

更好的做法是不要硬编码项目编号,而是实际读取项目名称并选择正确的项目名称,这样即使菜单更改也能正常工作。这只是对未来改进的一个注释。在

编辑 这就是在Python中实现同样的功能的方法。在

^{pr2}$

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

相关问题 更多 >