簡體   English   中英

使用Selenium / Beautiful Soup- Python從“下拉菜單”中提取選項值

[英]Extract option values from 'drop down menu' using Selenium/Beautiful Soup- Python

我需要從以下鏈接中提取年份,汽車型號和汽車數據: https : //auto-buy.geico.com/nb#/sale/vehicle/gskmsi/

以下是我到目前為止的代碼:

from selenium import webdriver
from selenium.webdriver.support import ui
from selenium.common.exceptions import TimeoutException
chromedriver = "D:\Codes\Webscraping\chromedriver.exe"



driver=webdriver.Chrome(executable_path=chromedriver)

try:
    driver.set_page_load_timeout(100)
    driver.get('https://auto-buy.geico.com/nb#/sale/vehicle/gskmsi/')
    select_element = ui.Select(ui.WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "vehicleYear"))))
    select_element.select_by_visible_text("2017")
    time.sleep(5)
    select_element = ui.Select(ui.WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "vehicleMake"))))
    select_element.select_by_visible_text("Acura")
    time.sleep(5)
    select_element = ui.Select(ui.WebDriverWait(driver, 10).until(EC.visibility_of_element_located((By.ID, "vehicleModel"))))
    select_element.select_by_visible_text("ILX")
    for i in driver.find_elements_by_xpath("//*[@id='vehicleMake']"):
        print (i.get_attribute("value"))
    select_box = Select(driver.find_element_by_xpath("//select[@class='vehicleMake']"))
    # get all options
    options = select_box.options
    print(options)    
except TimeoutException as ex:
    isrunning = 0
    print("Exception has been thrown. " + str(ex))
    driver.close()

注意:在運行代碼時,將加載第一個客戶信息頁面,您可以在其中隨機填寫郵政編碼75002

我的問題在於,現在如何從網站中提取年份,汽車型號和汽車品牌的所有值? 硒有幫助嗎? 或者我現在使用美麗湯嗎? 任何與代碼相關的幫助都將非常有用。

編輯:這樣我沒有任何錯誤。 我只是不知道用於提取年份,汽車型號和制造商的值的代碼

最大的問題是,僅在選擇Year后才填充Make。 僅在選擇年份后填充模型。 您將必須遍歷每個下拉列表以檢索所有值。 我不會提供完整的代碼,但是應該很簡單。 首先從“年份”下拉列表及其值開始

year_dropdown = driver.find_element_by_xpath('//select[@id="vehicleYear"]')
years = [year.text for year in year_dropdown.find_elements_by_tag_name('option')]

您將獲得一個空白值作為此列表中的第一項,因為下拉列表中的第一項為空白。 您可以選擇刪除它:

years = years[1:]

或者,一種更安全的方法:

years = [year for year in years if year]

此方法將僅將不為空的值保留在列表中。

因為您將不得不遍歷下拉列表中的年份:

for year in years:
    year_dropdown.find_element_by_xpath('.//option[text()="%s"]' % year).click()

在該for循環中,您現在必須做同樣的事情,但要進行make:

make_dropdown = driver.find_element_by_xpath('//select[@id="vehicleMake"]')
makes = [make.text for year in year_dropdown.find_elements_by_tag_name('option')]

看到我們要去哪里? 您現在要重復與“年份”下拉列表相同的代碼,但要重復“制作”。 您將對模型執行相同的操作。 您的流程最終將像:

for year in years:
    for make in makes:
        for model in models:
           ...

但是,我們不知道的是您打算對提取的數據進行什么處理,因此我無法為您提供輸出。 但這是提取數據的方式。 請注意,每個for循環迭代都將覆蓋其子列表。 因此makes經過一年的迭代后, models將被覆蓋,而經過迭代的models將覆蓋每個models

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM