上一节进行了网页的简单抓取,接下来我们详细的了解一下两个重要的参数url与data
urlopen详解
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None
URL参数
Open the URL url, which can be either a string or a Request object.
大概意思:URL参数不仅可以是一个字符串也可以是一个对象
data参数
data may be a bytes object specifying additional data to send to the server, or None if no such data is needed. data may also be an iterable object and in that case Content-Length value must be specified in the headers. Currently HTTP requests are the only ones that use data; the HTTP request will be a POST instead of a GET when the data parameter is provided. data should be a buffer in the standard application/x-www-form-urlencoded format. The urllib.parse.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format. urllib.request module uses HTTP/1.1 and includes Connection:close header in its HTTP requests.
大概意思:如果没有设置urlopen()函数的data参数,HTTP请求采用GET方式,也就是我们从服务器获取信息,如果我们设置data参数,HTTP请求采用POST方式,也就是我们向服务器传递数据。data参数有自己的格式,它是一个基于application/x-www.form-urlencoded的格式, 因为我们可以使用urllib.parse.urlencode()函数将字符串自动转换成上面所说的格式。
对象作为urlopen参数
urlopen返回的对象不仅可以使用read()进行读取,同时也可以使用geturl(),info(),getcode()方法
geturl()返回的是一个url的字符串;
info()返回的是一些meta标记的元信息,包括一些服务器的信息;
getcode()返回的是HTTP的状态码,如果返回200表示请求成功。
# -*- coding:UTF-8 -*-
from urllib import request
if __name__ == '__main__':
req = request.Request("http://cn.bing.com/translator?ref=MSTToolbar")
response = request.urlopen(req)
#geturl
print("geturl打印信息:%s"%(response.geturl()))
print('***************************************')
#info
print("info打印信息:%s"%(response.info()))
print('***************************************')
#getcode
print("getcode打印信息:%s"%(response.getcode()))
打印结果:
发送data示例
下面是一个向百度翻译传输数据并返回结果的例子:
# -*- coding:UTF-8 -*-
from urllib import request,parse
import json
if __name__ == '__main__':
#对应上图的url
Request_URL = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=https://www.baidu.com/link'
#创建字典
Form_Data = {}
Form_Data[type] = 'AUTO'
Form_Data['i'] = 'My name is Alice'
Form_Data['doctype'] = 'json'
Form_Data['xmlVersion'] = '1.8'
Form_Data['keyform'] = 'fanyi.web'
Form_Data['ue'] = 'ue:utf-8'
Form_Data['action'] = 'FY_BY_CLICKBUTTON'
#使用urlcode转换后的标准格式
data = parse.urlencode(Form_Data).encode("utf-8")
response = request.urlopen(Request_URL,data)
html = response.read().decode("utf-8")
translate_results = json.loads(html)
translate_results = translate_results['translateResult'][0][0]['tgt']
print(translate_results)
执行结果如下: