![Python Automation Cookbook](https://wfqqreader-1252317822.image.myqcloud.com/cover/411/36699411/b_36699411.jpg)
上QQ阅读APP看书,第一时间看更新
How to do it...
- Import requests, BeautifulSoup, and re modules:
>>> import requests
>>> from bs4 import BeautifulSoup
>>> import re
- Retrieve the form page, parse it, and print the input fields. Check that the posting URL is /post (not /forms/post):
>>> response = requests.get('https://httpbin.org/forms/post')
>>> page = BeautifulSoup(response.text)
>>> form = soup.find('form')
>>> {field.get('name') for field in form.find_all(re.compile('input|textarea'))}
{'delivery', 'topping', 'size', 'custemail', 'comments', 'custtel', 'custname'}
Note textarea is a valid input, as well as defined in the HTML format.
- Prepare the data to be posted as a dictionary. Check the values are the same as defined in the form:
>>> data = {'custname': "Sean O'Connell", 'custtel': '123-456-789', 'custemail': 'sean@oconnell.ie', 'size': 'small', 'topping': ['bacon', 'onion'], 'delivery': '20:30', 'comments': ''}
- Post the values and check that the response is the same as returned in the browser:
>>> response = requests.post('https://httpbin.org/post', data)
>>> response
<Response [200]>
>>> response.json()
{'args': {}, 'data': '', 'files': {}, 'form': {'comments': '', 'custemail': 'sean@oconnell.ie', 'custname': "Sean O'Connell", 'custtel': '123-456-789', 'delivery': '20:30', 'size': 'small', 'topping': ['bacon', 'onion']}, 'headers': {'Accept': '*/*', 'Accept-Encoding': 'gzip, deflate', 'Connection': 'close', 'Content-Length':
'140', 'Content-Type': 'application/x-www-form-urlencoded', 'Host': 'httpbin.org', 'User-Agent': 'python-requests/2.18.3'}, 'json': None, 'origin': '89.100.17.159', 'url': 'https://httpbin.org/post'}