我正在尝试使用selenium在https://www.wg-gesucht.de/en/和后续链接中输入表单。以下是我的代码
from selenium import webdriver
URL = "https://www.wg-gesucht.de/en/"
driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.get(URL)
#driver.find_element_by_xpath("//input[@id='date_from_input']").send_keys('31/08/2017')
#driver.find_element_by_xpath("//input[@id='date_to_input']").send_keys('01/09/2017')
driver.find_element_by_xpath("//input[@id='autocompinp']").send_keys('Berlin')
driver.find_element_by_xpath("//button[@id='rubrik-dropdown-menu']").click()
l1 = driver.find_element_by_xpath("//li[@data-text='Flatshares']")
driver.execute_script("arguments[0].click();", l1)
driver.find_element_by_xpath("//button[@id='ang-ges-dropdown-menu']").click()
l2 = driver.find_element_by_xpath("//li[@data-text='Offers']")
driver.execute_script("arguments[0].click();", l2)
driver.find_element_by_xpath("//input[@id='search_button']").click()
driver.find_element_by_xpath("//input[@id='rMax']").send_keys('400')
cmd_d1 = driver.find_element_by_xpath("//input[@id='date_from_input']").value= '31/08/2017'
driver.execute_script(cmd_d1)
cmd_d2 = driver.find_element_by_xpath("//input[@id='date_to_input']").value = '01/09/2017'
driver.execute_script(cmd_d2)
除了隐藏在More Options
按钮中的日期字段外,它的工作正常。如何插入值?
答案 0 :(得分:2)
选项1 - 点击“更多选项”'单击以展开窗体,使日期输入字段可见
// click 'More Options' click
driver.find_element_by_css_selector('a.show_more_filters').click()
// input begin date
driver.find_element_by_css_selector('#date_from_input').send_keys('31/08/2017')
// input end date
driver.find_element_by_css_selector('#date_to_input').send_keys('01/09/2017')
短缺:send_keys()可能会触发datepicker弹出窗口并且无法正常关闭, 未关闭的datepicker将阻止输入地址和距离文本框
选项2 - 使用execute_script()在浏览器上注入和执行javascript以设置日期输入字段的值作为静默方式。
// click 'More Options' click
driver.find_element_by_css_selector('a.show_more_filters').click()
// input begin date
begin_date_ele = driver.find_element_by_css_selector('#date_from_input')
driver.execute_script('arguments[0].value=arguments[1]', begin_date_ele, '31/08/2017')
// input end date
end_date_ele = driver.find_element_by_css_selector('#date_to_input')
driver.execute_script('arguments[0].value=arguments[1]', end_date_ele, '01/09/2017')