【问题标题】:Selenium error: Message: Select only works on <select> elements, not on <md-select>Selenium 错误:消息:选择仅适用于 <select> 元素,不适用于 <md-select>
【发布时间】:2021-07-01 19:12:18
【问题描述】:

我知道我应该找到“选择”元素,这样我就可以从下拉列表中进行选择,但是这里的谷歌趋势不提供“选择”元素,我想从数据和时间列表中选择任何值,当我尝试这样做我得到了这个错误'消息:选择只适用于元素,而不是'....我找到了一个解决方案,但它是由'请求'模块编写的,我想使用硒

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

from selenium.webdriver.support.ui import Select
import time

driver = webdriver.Chrome(executable_path="C:\\Drivers\\chromedriver.exe")


driver.get("https://trends.google.com/trends")

key1 = driver.find_element_by_xpath('//*[@id="sidenav-menu-btn"]/div')
key1.click()
time.sleep(1)

key2 = driver.find_element_by_xpath('//*[@id="sidenav-list-group-trends"]/md-item[2]/md-item-content/a/i')
key2.click()
time.sleep(2)


x = driver.find_element_by_xpath('//*[@id="select_12"]')
x.click()

drp = Select(x)
drp.select_by_index(2)

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    直接通过id 抓取它们,而不是使用select

    drp = driver.find_element_by_id("select_option_22") # equates to 'Past 5 years'
    drp.click()
    

    点击时打开过去 5 年(使用独特的 id

    drp = driver.find_element_by_id("select_option_20") # equates to 'Past 30 days'
    

    将是过去 30 天的菜单选项,等等....

    或者,你可以直接去找文字...

    drp = driver.find_element_by_xpath("//div[normalize-space(text())='Past 7 days']")
    drp.click()
    

    注意normalize-space,它用于去除该元素文本值所具有的空白。没有它就行不通。

    【讨论】:

    • 你能告诉我如何在谷歌趋势的国家下拉列表中获得“美国”的ID.....所以我可以选择它
    • 试试这个 xpath://md-option[@id='select_option_4']
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    • 1970-01-01
    • 2020-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多