使用 Selenium 在网站中输入数据?

Using Selenium to input a data in a website?

我希望每个人都过得愉快... 我的一位客户希望我创建一个程序来接收用户的输入并将其输入保险公司的网站,然后比较结果以找到最适合用户的费率。

我已经为两家公司做过,但是第三家真的很难输入文本,因为它是一个下拉列表。我输入了文字,但它没有进入下一页...请协助我,我很抱歉打扰你!!

代码

from selenium import webdriver
import os
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common import keys
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.keys import Keys
import time

PATH= "F:\chromedriver_win32\chromedriver.exe"

driver = webdriver.Chrome(PATH)
driver.get("")

search = WebDriverWait(driver, 30).until(
    EC.presence_of_element_located((By.ID, "zipcodeInput"))
)
search.send_keys('34997')
search.send_keys(Keys.RETURN)


element1 = driver.find_element_by_css_selector("#tt-fe8cbbe5-688b-40c3-4ce5-fdb588b05559_listbox > div.tt-dataset.tt-dataset-car_year")
drp = Select(element1)
drp.select_by_visible_text("2016")

# element1.send_keys("2016")
# element1.send_keys(Keys.RETURN)

element2 = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "#typeahead-input > div > span.twitter-typeahead > input:nth-child(2)"))
)
element2.send_keys(' BMW')
element2.send_keys(Keys.RETURN)
element3 = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "#typeahead-input > div > span.twitter-typeahead > input:nth-child(2)"))
)
element3.send_keys(' 4-Series')
element3.send_keys(Keys.RETURN)
element4 = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "#typeahead-input > div > span.twitter-typeahead > input:nth-child(2)"))
)
element4.send_keys(' 428i')
element4.send_keys(Keys.RETURN)
time.sleep(10)
element5 = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "#typeahead-input > div > span.twitter-typeahead > input:nth-child(2)"))
)
element5.send_keys(" Grain Coupe")
element5.send_keys(Keys.RETURN)
time.sleep(50)

choose = WebDriverWait(driver, 10).until(
    EC.presence_of_element_located((By.CSS_SELECTOR, "#used_for_work > span"))
)

choose.click()

Image

您不能使用 Select(element1) 因为 element1 不是 select node/tag 而是 div,即能够使用 Select 你应该

<select role="presentation" class="tt-dataset tt-dataset-car_year">

而不是

<div role="presentation" class="tt-dataset tt-dataset-car_year">

你要做的是

year = 2016
selection = driver.find_element_by_xpath(f'//div[contains(@class, "tt-dataset-car_year")]/child::div[contains(text(), "{year}")]')
selection.click()