python爬虫学习2_urlLib基本使用
urlLib库
在urlLib应用在python3.0之后。
常用api里面的方法有:
-
urllib.request模块是用来打开和读取URLs的;
-
urllib.error模块包含一些有urllib.request产生的错误,可以使用try进行捕捉处理;
-
urllib.parse模块包含了一些解析URLs的方法;
-
urllib.robotparser模块用来解析robots.txt文本文件.它提供了一个单独的RobotFileParser类,通过该类提供的can_fetch()方法测试爬虫是否可以下载一个页面。
urllib.request.Request(url, data=None, headers={}, method=None)
url = r'http://www.lagou.com/zhaopin/Python/?labelWords=label'
headers = {
'User-Agent':
r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
'Connection': 'keep-alive'
}
req = request.Request(url, headers=headers)
page = request.urlopen(req).read()
page = page.decode('utf-8')
用来包装头部的数据:
-
User-Agent :这个头部可以携带如下几条信息:浏览器名和版本号、操作系统名和版本号、默认语言
-
Referer:可以用来防止盗链,有一些网站图片显示来源http://***.com,就是检查Referer来鉴定的
-
Connection:表示连接状态,记录Session的状态。
返回数据处理:
urllib.request请求之后的数据是返回的网页数据,它的处理可以有:
1、decode可以这个api处理为我们可读的数据:
response = request.urlopen("http://www.fanyi.baidu.com/")
html = response.read()
html = html.decode("utf-8")
2、geturl()返回的是一个url的字符串;
3、info()返回的是一些meta标记的元信息,包括一些服务器的信息;
4、getcode()返回的是HTTP的状态码,如果返回200表示请求成功。
if __name__ == "__main__":
req = request.Request("http://fanyi.baidu.com/")
response = request.urlopen(req)
print("geturl打印信息:%s"%(response.geturl()))
print('**********************************************')
print("info打印信息:%s"%(response.info()))
print('**********************************************')
print("getcode打印信息:%s"%(response.getcode()))
5、read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作
小demo
百度翻译:
# -*- coding: UTF-8 -*-
from urllib import request
from urllib import parse
import json
if __name__ == "__main__":
# 对应上图的Request URL
request_url = "http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule"
# 创建Form Data字典,存储上图中的Form Data
Form_Data = {}
Form_Data['i'] = 'Jack'
Form_Data['from'] = 'AUTO'
Form_Data['to'] = 'AUTO'
Form_Data['smartresult'] = 'dict'
Form_Data['client'] = 'fanyideskweb'
Form_Data['doctype'] = 'json'
Form_Data['version'] = '2.1'
Form_Data['keyfrom'] = 'fanyi.web'
Form_Data['action'] = 'FY_BY_REALTIME'
Form_Data['typoResult'] = 'false'
# 使用urlencode方法转换标准格式
data = parse.urlencode(Form_Data).encode('utf-8')
# 传递Request对象和转换完格式的数据
response = request.urlopen(request_url, data)
# 读取信息并解码
html = response.read().decode('utf-8')
# 使用json
translate_results = json.loads(html)
# 找到翻译结果
translate_result = translate_results["translateResult"][0][0]['tgt']
# 打印翻译结果
print("翻译的结果是 %s" % translate_result)

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



