首页 > 解决方案 > 如何使用 Selenium 和 Python 覆盖默认输入字段值

问题描述

我正在使用 python 和 selenium 来抓取这个网站,我需要覆盖 zipcode 字段中的默认值。我已经使用了该.clear()方法,然后尝试使用该send_keys()函数发送我自己的值,但默认邮政编码仍保留在输入字段中。有谁知道如何解决这个问题?下面是我的代码:

from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from webdriver_manager import driver
from webdriver_manager.chrome import ChromeDriverManager
radius = int(input("Enter the radius: "))
zipcode = int(input("Enter your zipcode"))

url = f'https://www.edmunds.com/cars-for-sale-by-owner/'

options = Options()
options.headless = False
options.add_experimental_option("detach", True)

browser = webdriver.Chrome(ChromeDriverManager().install(), options=options)
browser.maximize_window()
browser.get(url)
browser.set_page_load_timeout(15)

zipcode_form = browser.find_element_by_name('zip')
zipcode_form.clear() #This is meant to clear the default value in the zipcode field
zipcode_form.send_keys(str(zipcode)) #This is enter the zipcode value I provided in the zipcode field
zipcode_form.send_keys(Keys.RETURN) #I did this because there is no button to click after filling the zipcode form on the website and pressing enter works instead

... # The rest of my code which extracts the information I want

我刚开始学习硒,如果我犯了任何愚蠢的错误,请原谅我。

标签: pythonseleniumselenium-webdriver

解决方案


我建议通过 ID 查找驱动程序元素,因为它是该元素独有的:

driver.find_element_by_id('zip').clear()

推荐阅读