首页 > 解决方案 > 如何使用 selenium 填写 html 表单?

问题描述

url = http://ptvtelecom.com/ 如果您按照 url 并单击显示“combrobar”的按钮,该按钮应该在屏幕中间可见,它会将您带到需要填写的表格。我想知道如何使用硒填写表格。

所以我已经尝试通过 id 和 name 查找元素,但它不起作用。例如,关于如何找到第一个文本框的元素的任何帮助都会非常有用。

option = webdriver.ChromeOptions()
option.add_argument(" — incognito")
browser = 
webdriver.Chrome(executable_path='/Users/grsanchez/downloads/chromedriverM', 
options=option)
browser.get('http://ptvtelecom.com/')
browser.find_element_by_xpath('//* 
[@id="cobertura"]/div/div[2]/div/div/p/a').click()

这是出错的地方

name = browser.find_element_by_id('nombre')
name.send_keys('user1')

标签: pythonhtmlselenium

解决方案


阅读代码中的注释以了解您的代码为何不起作用。
基本上,您正在尝试选择 iframe 中存在的内容。

option = webdriver.ChromeOptions()
option.add_argument("--incognito")

browser = webdriver.Chrome(executable_path='/Users/grsanchez/downloads/chromedriverM', 
options=option)

browser.get('http://ptvtelecom.com/')

## finding the button that shows the form
btn = browser.find_element_by_css_selector('#cobertura .boton-cobertura')

## using js to click it, to avoid getting issues in case the button wasn't visible
driver.execute_script("arguments[0].click();", btn)

## the element you want to select is actually inside an iframe, so we need to switch to it, if we want to select anything
driver.switch_to.frame(driver.find_element_by_css_selector('#popmake-1432 iframe'));

## selecting the name input and sending a string
name = driver.find_element_by_css_selector('#nombre')
name.send_keys('user1')

PS返回主框架,你可以这样做:

driver.switch_to.default_content()

推荐阅读