AttributeError: 'WebElement' object has no attribute 'select_by_value' selecting dropdown menu using Selenium

AttributeError: 'WebElement' object has no attribute 'select_by_value' selecting dropdown menu using Selenium

我正在尝试从 website 中按不同的州查找某些快餐店的菜单价格。有一个下拉菜单,其中有不同的状态选项。在我 select 一个州(例如加利福尼亚州)之后,我想通过网络抓取他们冰淇淋的不同价格。但是,我不断收到相同的错误消息,阻止我获取数据。我认为在访问该网站之前它工作正常,但它似乎无法按状态 select。我需要做什么才能:

  1. 获取 selenium 以准确 select 某个州(加利福尼亚州)
  2. 仅获取“冰淇淋”类别的菜单价格?

代码如下:

!pip3 install selenium
!pip3 install webdriver-manager

from selenium import webdriver
import time 
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
import pandas as pd

path = ("C:/path/to/chromedriver.exe")

driver = webdriver.Chrome(executable_path = path)
url = "https://www.fastfoodmenuprices.com/baskin-robbins-prices/"
driver.get(url)
select_state = driver.find_element_by_xpath("//select[@class='tp-variation']").click
## select_state = driver.find_element_by_id("variation-tablepress-34")
select_state = driver.find_element_by_id("variation-tablepress-34")
select_state.select_by_value("MS4yOA==")
time.sleep(3)

我得到的错误是:

AttributeError: 'WebElement' object has no attribute 'select_by_value'

代码+错误的照片如下:

select_by_value() is a method from select class and to use it you have to use the Select(webelement) 方法。


解决方案

要select选项加州你可以使用下面的:

  • 代码块:

    driver.get("https://www.fastfoodmenuprices.com/baskin-robbins-prices")
    Select(WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.XPATH, "//select[@class='tp-variation']")))).select_by_value("MS4yOA==")
    
  • 浏览器快照: