5imobi 发表于 2018-8-11 13:52:44

Python学习笔记__12.9章 urlib

  # 这是学习廖雪峰老师python教程的学习笔记
  1、概览
  urllib提供了一系列用于操作URL的功能。
  urllib中包括了四个模块,包括

[*]  urllib.request:可以用来发送request和获取request的结果
[*]  urllib.error:包含了urllib.request产生的异常
[*]  urllib.parse:用来解析和处理URL
[*]  urllib.robotparse:用来解析页面的robots.txt文件
  1.1、urllib.request
  urllib的request模块可以非常方便地抓取URL内容。
  它会先发送一个GET请求到指定的页面,然后返回HTTP的响应:
  1)对豆瓣的一个URL进行抓取,并返回响应
  from urllib import request
  # request模块调用urlopen方法打开网址
  with request.urlopen('https://api.douban.com/v2/book/2129650') as f:
  data = f.read() #返回的网页内容
  print('Status:', f.status, f.reason)
  for k, v in f.getheaders():
  print('%s: %s' % (k, v))
  print('Data:', data.decode('utf-8'))
  2)模拟iPhone 6去请求豆瓣首页
  模拟浏览器发送GET请求,使用Request对象。通过往Request对象添加HTTP头,我们就可以把请求伪装成各种浏览器
  from urllib import request
  req = request.Request('http://www.douban.com/') #创建了一个Request对象 req是类
  # 添加请求的头信息
  req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
  with request.urlopen(req) as f: #将Request对象作为url传入
  print('Status:', f.status, f.reason)
  for k, v in f.getheaders():
  print('%s: %s' % (k, v))
  print('Data:', f.read().decode('utf-8'))
  1.2、Post
  如果要以POST发送一个请求,只需要把参数data以bytes形式传入。
  1)我们模拟一个微博登录,先读取登录的邮箱和口令,然后按照weibo.cn的登录页的格式以username=xxx&password=xxx的编码传入
  from urllib import request, parse
  print('Login to weibo.cn...')
  email = input('Email: ')
  passwd = input('Password: ')
  login_data = parse.urlencode([# 用parse的urlencode方法,对要传过去的数据进行编码
  ('username', email),
  ('password', passwd),
  ('entry', 'mweibo'),
  ('client_id', ''),
  ('savestate', '1'),
  ('ec', ''),
  ('pagerefer', 'https://passport.weibo.cn/signin/welcome?entry=mweibo&r=http%3A%2F%2Fm.weibo.cn%2F')
  ])
  req = request.Request('https://passport.weibo.cn/sso/login')   # 创建Request 对象
  req.add_header('Origin', 'https://passport.weibo.cn')
  req.add_header('User-Agent', 'Mozilla/6.0 (iPhone; CPU iPhone OS 8_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/8.0 Mobile/10A5376e Safari/8536.25')
  req.add_header('Referer', 'https://passport.weibo.cn/signin/login?entry=mweibo&res=wel&wm=3349&r=http%3A%2F%2Fm.weibo.cn%2F')
  with request.urlopen(req, data=login_data.encode('utf-8')) as f: #data用来指明发往服务器请求中的额外的信息
  print('Status:', f.status, f.reason)
  for k, v in f.getheaders():
  print('%s: %s' % (k, v))
  print('Data:', f.read().decode('utf-8'))
  1.3、Header
  1)如果还需要更复杂的控制,比如通过一个Proxy去访问网站,我们需要利用ProxyHandler来处理
  proxy_handler = urllib.request.ProxyHandler({'http': 'http://www.example.com:3128/'}) #创建代理
  proxy_auth_handler = urllib.request.ProxyBasicAuthHandler()#设置基础认证管理,用代理处理身份认证

  #>  # 用一个使用编程提供的代理url(’host‘)替换默认的ProxyHandler
  proxy_auth_handler.add_password('realm', 'host', 'username', 'password')
  opener = urllib.request.build_opener(proxy_handler, proxy_auth_handler) # 返回一个 OpenerDirector 实例
  with opener.open('http://www.example.com/login.html') as f:# 访问网址
  pass
  1.4、小结
  urllib提供的功能就是利用程序去执行各种HTTP请求。如果要模拟浏览器完成特定功能,需要把请求伪装成浏览器。伪装的方法是先监控浏览器发出的请求,再根据浏览器的请求头来伪装,User-Agent头就是用来标识浏览器的。
  1.5、扩展文档
  python3网络爬虫一《使用urllib.request发送请求》 (https://blog.csdn.net/bo_mask/article/details/76067790)
  Python中urlopen()介绍 (https://www.cnblogs.com/zyq-blog/p/5606760.html)
  python 爬虫之为什么使用opener对象以及为什么要创建全局默认的opener对象 (https://www.cnblogs.com/cunyusup/p/7341829.html)
  2、例子
  1、利用urllib读取JSON,然后将JSON解析为Python对象:
  # -*- coding: utf-8 -*-
  from urllib import request
  import json
  def fetch_data(url):
  with request.urlopen(url) as f:
  data = json.loads(f.read().decode('utf-8')) #将读到的网页内容解码,再由json.loads()反序列化为Python对象
  return data
  # 测试
  URL = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid%20%3D%202151330&format=json'
  data = fetch_data(URL)
  print(data)
  assert data['query']['results']['channel']['location']['city'] == 'Beijing'
  print('ok')
页: [1]
查看完整版本: Python学习笔记__12.9章 urlib