urllib.request 模块定义了一些类及方法,用于帮助我们访问URL
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False)
方法是用来打开url的方法,其中url可以是一个合法的url字符串,或者是一个request对象;data必须是字节数据类型的。详细介绍可参见python3官方文档urllib.request。
关于数据提交的两种方式get、post的区别,在此就不再赘述,下面给出两种提交方式的例子:
Get:
# ----------------------------------
__author__ = 'zWX231671'
__description__ = ''
# ----------------------------------
import urllib.parse
import urllib.request
data = urllib.parse.urlencode({'name': 'abc', 'password': '123'})
response = urllib.request.urlopen('http://127.0.0.1:8080/test/index.jsp?%s' % data)
html = response.read()
print(html.decode('utf-8'))
Post:
# ----------------------------------
__author__ = 'zWX231671'
__description__ = ''
# ----------------------------------
import urllib.parse
import urllib.request
url = 'http://127.0.0.1:8080/test/index.jsp'
user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'
values = {
'name': 'abc',
'password': '123'
}
data = urllib.parse.urlencode(values)
# that params output from urlencode is encoded to bytes before it is sent to urlopen as data
data = data.encode('utf-8')
req = urllib.request.Request(url, data)
response = urllib.request.urlopen(req)
html = response.read()
print(html.decode('utf-8'))