![Python Automation Cookbook](https://wfqqreader-1252317822.image.myqcloud.com/cover/411/36699411/b_36699411.jpg)
上QQ阅读APP看书,第一时间看更新
How to do it...
- Import Selenium, start a browser, and load the form page. A page will open reflecting the operations:
>>> from selenium import webdriver
>>> browser = webdriver.Chrome()
>>> browser.get('https://httpbin.org/forms/post')
Note the banner with Chrome is being controlled by automated test software.
- Add a value in the Customer name field. Remember that it is called custname:
>>> custname = browser.find_element_by_name("custname")
>>> custname.clear()
>>> custname.send_keys("Sean O'Connell")
The form will update:
![](https://epubservercos.yuewen.com/B3CCD2/19470388401537106/epubprivate/OEBPS/Images/13d8d74f-9f2e-4ef9-87e1-29deb1c70b95.png?sign=1740123006-C71Lpo80pCdVBYWSVulYB18byqKmoSqy-0-b80911eabd0e3906a81b9a5eadacc0b4)
- Select the pizza size as medium:
>>> for size_element in browser.find_elements_by_name("size"):
... if size_element.get_attribute('value') == 'medium':
... size_element.click()
...
>>>
This will change the pizza size ratio box.
- Add bacon and cheese:
>>> for topping in browser.find_elements_by_name('topping'):
... if topping.get_attribute('value') in ['bacon', 'cheese']:
... topping.click()
...
>>>
Finally, the checkboxes will appear as marked:
![](https://epubservercos.yuewen.com/B3CCD2/19470388401537106/epubprivate/OEBPS/Images/789403c5-3c8f-4c14-b9c5-6318286ae9c1.png?sign=1740123006-yPBrkECp6RucCcZz0Jcka7PB2S33dY6C-0-2254cf4a383e96c51f5a6b23683b76e7)
- Submit the form. The page will submit and the result will be displayed:
>>> browser.find_element_by_tag_name('form').submit()
The form will be submitted and the result from the server will be displayed:
![](https://epubservercos.yuewen.com/B3CCD2/19470388401537106/epubprivate/OEBPS/Images/b9063025-2521-4820-a446-90e9d89b4dbd.png?sign=1740123006-loEDZshRsw7QedBiAxgZV1jtzWQqDBT1-0-c8286f316553ff2238d5e66cdeecfeb3)
- Close the browser:
>>> browser.quit()