如何使用Selenium填写html表单?

时间:2019-04-20 23:11:44

标签: python html selenium

url = http://ptvtelecom.com/ 如果您跟随该网址,然后单击显示在屏幕中间的“ 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')

2 个答案:

答案 0 :(得分:3)

阅读代码中的注释,以了解代码为何无法正常工作。
基本上,您正在尝试选择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()

答案 1 :(得分:-1)

您需要将类似driver.switchTo()。frame(“ a077aa5e”);的内容切换到iframe;

然后在iframe中使用定位器