我需要从以下链接提取年份、车型和汽车数据: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()注意:运行代码时,将加载第一个客户信息页面,您可以使用zip 75002随机填充该页面
我的问题是,我现在如何从站点中提取所有的年份、车型和汽车制造的值?硒在这方面有帮助吗?或者我现在用美汤?任何与代码相关的帮助都会很棒。
编辑:我在代码中没有任何错误。我只是不知道提取年份、车型和汽车提前致谢的代码
发布于 2018-01-18 08:16:42
最大的问题是,Make只在选择了Year之后才会填充。仅当选择年份后,才会填充模型。您将不得不遍历每个下拉列表以检索所有值。我不会提供完整的代码,但它应该非常简单。首先从获取年份下拉列表及其值开始
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')]明白我们要做什么了吗?您现在正在重复与Year dropdown中相同的代码,但不是Make。您将对Model执行相同的操作。你的流程最终会是这样的:
for year in years:
for make in makes:
for model in models:
...然而,我们不知道的是,您计划如何处理提取的数据,因此我无法帮助您处理输出。但这是您提取数据的方法。请注意,每次for循环迭代都会覆盖它的子列表。因此,makes将在迭代一年后被覆盖,并且每个models将在make被迭代后被覆盖。
https://stackoverflow.com/questions/48286382
复制相似问题