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'))

本文详细介绍了使用urllib.request模块打开URL的方法,并通过实例展示了GET和POST两种数据提交方式的应用。GET方法用于简单地获取数据,而POST方法则适用于更复杂的数据交互。
--Python3数据get与post提交&spm=1001.2101.3001.5002&articleId=38865113&d=1&t=3&u=7d13849b7387454fbbb9114dd1b5ebc7)
1281

被折叠的 条评论
为什么被折叠?



