python - 抓取下拉列表提取值的所有组合

标签 python selenium web-scraping

我正在尝试从 cars.com 中提取价格信息和 h1 标签信息,有一个下拉列表可以搜索该页面。

我想选择不同的型号并搜索价格。但“型号”的选择取决于“品牌”。我有使用 Selenium 的下拉菜单的所有组合。 对于每个下拉组合,如何获取 H1 信息,例如“soup.find("H1")"

代码如下

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

driver = webdriver.Chrome('C:/Users/chromedriver.exe')
driver.get('https://www.cars.com/')
time.sleep(4)

selectMake = Select(driver.find_element_by_name("makeId"))


time.sleep(2)


selectModel = Select(driver.find_element_by_name("modelId"))

data = []
for makesOption in selectMake.options:
    makesText = makesOption.text
    selectMake.select_by_visible_text(makesText)
    time.sleep(1)
    selectModel = Select(driver.find_element_by_name("modelId"))
    for modelOption in selectModel.options:
        modelText = modelOption.text
        selectModel.select_by_visible_text(modelText)
        data.append([makesText,modelText])

最佳答案

您初始化Select但未选择任何内容,请查找如何使用 select here 的详细信息.

使用WebDriverWait您可以等待元素的具体情况。在下面的代码中,我使用了 wait.until(EC.element_to_be_clickable((By.NAME, "makeId"))) 而不是 sleep,其中 Selenium 将每隔 0.5 秒检查该元素是否可点击,并超时10 秒后,一旦满足可点击条件,就会继续前进。

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time

driver = webdriver.Chrome('C:/Users/chromedriver.exe')
wait = WebDriverWait(driver, 10)

driver.get('https://www.cars.com/')

select_make = Select(wait.until(EC.element_to_be_clickable((By.NAME, "makeId"))))
select_make.select_by_visible_text("BMW")

select_model = Select(wait.until(EC.element_to_be_clickable((By.NAME, "modelId"))))
select_model.select_by_visible_text("- M850 Gran Coupe")

关于python - 抓取下拉列表提取值的所有组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60345544/

相关文章:

python - 目录路径python中的空格

python - 如何从 Pyspark RDD 中删除空行

java - 如何在 Selenium Java 中使用键盘按键复制段落

Python 使用 lxml 下载图像

python - LXML:如何忽略未知的命名空间前缀?

python - 如何将基类的映射方法用于派生类?

firefox - 关闭 Firefox 13 中的内置 RSS 阅读器

javascript - PhantomJS 与 WebDriver

javascript - 使用 JavaScript 链接抓取网页

python - 避免在使用 scrapy 的网站上被禁止