0.爬虫 urlib库讲解 urlopen()与Request()
# 注意一下 是import urllib.request 还是 form urllib import request
0. urlopen()
语法:urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
- 实例0:(这个函数 一般就使用三个参数 url data timeout)
*添加的data参数需要使用bytes()方法将参数转换为字节流(区别于str的一种类型 是一种比特流 010010010)编码的格式的内容,即bytes类型。
*response.read()是bytes类型的数据,需要decode(解码)一下。
import urllib.parse import urllib.request import urllib.errorurl = 'http://httpbin.org/post' data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8') try:response = urllib.request.urlopen(url, data=data,timeout=1) except urllib.error.URLError as e:if isinstance(e.reason, socket.timeout):print('TIME OUT') else:print(response.read().decode("utf-8"))
输出结果:
{"args": {}, "data": "", "files": {}, "form": {"word": "hello"}, "headers": {"Accept-Encoding": "identity", "Content-Length": "10", "Content-Type": "application/x-www-form-urlencoded", "Host": "httpbin.org", "User-Agent": "Python-urllib/3.6"}, "json": null, "origin": "101.206.170.234, 101.206.170.234", "url": "https://httpbin.org/post"
}
- 实例1:查看i状态码、响应头、响应头里server字段的信息
import urllib.requestresponse = urllib.request.urlopen('https://www.python.org')
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))
输出结果:
200
[('Server', 'nginx'), ('Content-Type', 'text/html; charset=utf-8'), ('X-Frame-Options', 'DENY'), ('Via', '1.1 vegur'), ('Via', '1.1 varnish'), ('Content-Length', '48410'), ('Accept-Ranges', 'bytes'), ('Date', 'Tue, 09 Apr 2019 02:32:34 GMT'), ('Via', '1.1 varnish'), ('Age', '722'), ('Connection', 'close'), ('X-Served-By', 'cache-iad2126-IAD, cache-hnd18751-HND'), ('X-Cache', 'MISS, HIT'), ('X-Cache-Hits', '0, 1223'), ('X-Timer', 'S1554777154.210361,VS0,VE0'), ('Vary', 'Cookie'), ('Strict-Transport-Security', 'max-age=63072000; includeSubDomains')]
nginx
使用urllib库的urlopen()方法有很大的局限性,比如不能设置响应头的信息等。所以需要引入request()方法。
1. Request()
- 实例0:(这两种方法的实现效果是一样的)
import urllib.requestresponse = urllib.request.urlopen('https://www.python.org') print(response.read().decode('utf-8'))######################################import urllib.requestreq = urllib.request.Request('https://python.org') response = urllib.request.urlopen(req) print(response.read().decode('utf-8'))
下面主要讲解下使用Request()方法来实现get请求和post请求,并设置参数。
- 实例1:(post请求)
from urllib import request, parseurl = 'http://httpbin.org/post' headers = {'User-Agent': 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)','Host': 'httpbin.org' } dict = {'name': 'Germey' } data = bytes(parse.urlencode(dict), encoding='utf8') req = request.Request(url=url, data=data, headers=headers, method='POST') response = request.urlopen(req) print(response.read().decode('utf-8'))
亦可使用add_header()方法来添加报头,实现浏览器的模拟,添加data属性亦可如下书写:
补充:还可以使用bulid_opener()修改报头,不过多阐述,够用了就好。
from urllib import request, parseurl = 'http://httpbin.org/post' dict = {'name': 'Germey' } data = parse.urlencode(dict).encode('utf-8') req = request.Request(url=url, data=data, method='POST') req.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)') response = request.urlopen(req) print(response.read().decode('utf-8'))
- 实例2:(get请求) 百度关键字的查询
from urllib import request,parseurl = 'http://www.baidu.com/s?wd=' key = '路飞' key_code = parse.quote(key) url_all = url + key_code """ #第二种写法 url = 'http://www.baidu.com/s' key = '路飞' wd = parse.urlencode({'wd':key}) url_all = url + '?' + wd """ req = request.Request(url_all) response = request.urlopen(req) print(response.read().decode('utf-8'))
在这里,对编码decode、reqest模块里的quote()方法、urlencode()方法 等就有疑问了,,对此,做一些说明:
- parse.quote:将str数据转换为对应的编码
- parse.urlencode:将字典中的k:v转换为K:编码后的v
- parse.unquote:将编码后的数据转化为编码前的数据
- decode 字符串解码 decode("utf-8")跟read()搭配很配!
- encode 字符串编码
>>> str0 = '我爱你' >>> str1 = str0.encode('gb2312') >>> str1 b'\xce\xd2\xb0\xae\xc4\xe3' >>> str2 = str0.encode('gbk') >>> str2 b'\xce\xd2\xb0\xae\xc4\xe3' >>> str3 = str0.encode('utf-8') >>> str3 b'\xe6\x88\x91\xe7\x88\xb1\xe4\xbd\xa0' >>> str00 = str1.decode('gb2312') >>> str00 '我爱你' >>> str11 = str1.decode('utf-8') #报错,因为str1是gb2312编码的 Traceback (most recent call last):File "<pyshell#9>", line 1, in <module>str11 = str1.decode('utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xce in position 0: invalid continuation byte
* encoding指定编码格式
在这里,又有疑问了?read()、readline()、readlines()的区别:
- read():全部,字符串str
- reasline():一行
- readlines():全部,列表list
转载于:https://www.cnblogs.com/DC0307/p/10675878.html
0.爬虫 urlib库讲解 urlopen()与Request()相关推荐
- Python爬虫从入门到精通─第2课 Requests库讲解
本教程所有源码下载链接:share.weiyun.com/5xmFeUO 密码:fzwh6g 本教程版权归作者GitOPEN所有,转载请征求作者同意 本教程首发于GitOPEN's Home Requ ...
- 0.爬虫介绍及requests库的使用
1. 互联网知识介绍 互联网: 是由网络设备(网线, 路由器, 交换机, 防火墙...)和一台台计算机链接而成. 互联网建立的目的: 数据的共享/传递. 俗称的'上网': 由用户端计算机发送请求给目标 ...
- 爬虫工作流程、请求与响应原理、requests库讲解
爬虫工作流程.请求与响应原理.requests库讲解 爬虫分类主要分为两大板块 web爬虫(浏览器爬虫) APP爬虫(手机端爬虫) 在这两大板块中又可以把爬虫归类为聚焦爬虫和通用爬虫 聚焦爬虫:针对某 ...
- 爬虫_urllib2库的使用
爬虫_urllib2库的使用 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地. 在Python中有很多库可以用来抓取网页,我们先学习urllib2. urllib2 是 ...
- Python爬虫——Requests 库基本使用
文章目录 Python爬虫--Requests 库基本使用 1.Requests简介和下载 2.Requests 库基本使用 Python爬虫--Requests 库基本使用 1.Requests简介 ...
- Python爬虫5.3 — scrapy框架spider[Request和Response]模块的使用
Python爬虫5.3 - scrapy框架spider[Request和Response]模块的使用 综述 Request对象 scrapy.Request()函数讲解: Response对象 发送 ...
- python网络爬虫——爬虫第三方库的使用(二)
爬虫第三方库的使用 一.urllib库的介绍与使用 1.urlopen()方法 2.Request()方法 3.Robots协议 二.requests库的介绍与使用 1.GET请求 2.POST请求 ...
- 2.03_01_Python网络爬虫urllib2库
一:urllib2库的基本使用 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中抓取出来.在Python中有很多库可以用来抓取网页,我们先学习urllib2. urllib2 是 Python ...
- python爬虫学习笔记3.2-urllib和request练习
python爬虫学习笔记3.2-urllib和request练习 一.urllib练习 1.百度贴吧案例 需求 分析 手动测试查询流程 观察页面 分析特殊部分 https://tieba.baidu. ...
最新文章
- 面试官问:ZooKeeper 一致性协议 ZAB 原理
- pytorch下载时出现错误:EOFError: Compressed file ended before the end-of-stream marker was reached
- fail-fast(快速失败/报错机制)-ConcurrentModificationException
- c++进制转换代码_轻松实现C/C++各种常见进制相互转换,你还不会你就落后了
- java双语试卷_Java程序设计基础(双语)试题题目及答案,课程2021最新期末考试题库,章节测验答案...
- 批量上传文件及进度显示
- 深入理解Magento – 第五章 – Magento资源配置
- 基于LSTM搭建文本情感分类的深度学习模型:准确率95%
- android videoview截屏,android VideoView截屏黑屏解决方法
- 160603、使用pd4ml.jar和ss_css2.jar转pdf的工具类
- java.io.IOException: Unable to read entire header; 275 bytes read; expected 512 bytes
- 什么牌子的蓝牙耳机耐用?2023年最值得入手的蓝牙耳机分享
- coredata理解
- 任何事,尽量从正面、善意的角度去解读,运气都不会太差
- The rollout of the Indian motorcycle brand continues apace
- 锐捷智能感知“安全卫士”守护广东2000个基层医疗机构信息安全
- echats设置辅助线
- Adobe Creative Suite 3 Design Premium 中文版下载
- 迅闪2011安装指南
- 搜索引擎简介之数据采集篇