转载自:https://www.cnblogs.com/php-linux/p/8365941.html

1.基本方法

urllib.request.urlopen(urldata=None, [timeout, ]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

-         url:  需要打开的网址

-         data:Post提交的数据

-         timeout:设置网站的访问超时时间

直接用urllib.request模块的urlopen()获取页面,page的数据格式为bytes类型,需要decode()解码,转换成str类型。

1 from urllib import request
2 response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse类型
3 page = response.read()
4 page = page.decode('utf-8')

urlopen返回对象提供方法:

-         read() , readline() ,readlines() , fileno() , close() :对HTTPResponse类型数据进行操作

-         info():返回HTTPMessage对象,表示远程服务器返回的头信息

-         getcode():返回Http状态码。如果是http请求,200请求成功完成;404网址未找到

-         geturl():返回请求的url

2.使用Request

urllib.request.Request(url, data=None, headers={}, method=None)

使用request()来包装请求,再通过urlopen()获取页面。

 1 url = r'http://www.lagou.com/zhaopin/Python/?labelWords=label'
2 headers = {
3 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
4 r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
5 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
6 'Connection': 'keep-alive'
7 }
8 req = request.Request(url, headers=headers)
9 page = request.urlopen(req).read()
10 page = page.decode('utf-8')

用来包装头部的数据:

-         User-Agent :这个头部可以携带如下几条信息:浏览器名和版本号、操作系统名和版本号、默认语言

-         Referer:可以用来防止盗链,有一些网站图片显示来源http://***.com,就是检查Referer来鉴定的

-         Connection:表示连接状态,记录Session的状态。

3.Post数据

urllib.request.urlopen(urldata=None, [timeout, ]*cafile=Nonecapath=Nonecadefault=Falsecontext=None)

urlopen()的data参数默认为None,当data参数不为空的时候,urlopen()提交方式为Post。

 1 from urllib import request, parse
2 url = r'http://www.lagou.com/jobs/positionAjax.json?'
3 headers = {
4 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
5 r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
6 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
7 'Connection': 'keep-alive'
8 }
9 data = {
10 'first': 'true',
11 'pn': 1,
12 'kd': 'Python'
13 }
14 data = parse.urlencode(data).encode('utf-8')
15 req = request.Request(url, headers=headers, data=data)
16 page = request.urlopen(req).read()
17 page = page.decode('utf-8')

urllib.parse.urlencode(query, doseq=False, safe='', encoding=None, errors=None)

urlencode()主要作用就是将url附上要提交的数据。

1 data = {
2 'first': 'true',
3 'pn': 1,
4 'kd': 'Python'
5 }
6 data = parse.urlencode(data).encode('utf-8')

经过urlencode()转换后的data数据为?first=true?pn=1?kd=Python,最后提交的url为

http://www.lagou.com/jobs/positionAjax.json?first=true?pn=1?kd=Python

Post的数据必须是bytes或者iterable of bytes,不能是str,因此需要进行encode()编码

1 page = request.urlopen(req, data=data).read()

当然,也可以把data的数据封装在urlopen()参数中

4.异常处理

 1 def get_page(url):
2 headers = {
3 'User-Agent': r'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
4 r'Chrome/45.0.2454.85 Safari/537.36 115Browser/6.0.3',
5 'Referer': r'http://www.lagou.com/zhaopin/Python/?labelWords=label',
6 'Connection': 'keep-alive'
7 }
8 data = {
9 'first': 'true',
10 'pn': 1,
11 'kd': 'Python'
12 }
13 data = parse.urlencode(data).encode('utf-8')
14 req = request.Request(url, headers=headers)
15 try:
16 page = request.urlopen(req, data=data).read()
17 page = page.decode('utf-8')
18 except error.HTTPError as e:
19 print(e.code())
20 print(e.read().decode('utf-8'))
21 return page

5、使用代理

urllib.request.ProxyHandler(proxies=None)

当需要抓取的网站设置了访问限制,这时就需要用到代理来抓取数据。

 1 data = {
2 'first': 'true',
3 'pn': 1,
4 'kd': 'Python'
5 }
6 proxy = request.ProxyHandler({'http': '5.22.195.215:80'}) # 设置proxy
7 opener = request.build_opener(proxy) # 挂载opener
8 request.install_opener(opener) # 安装opener
9 data = parse.urlencode(data).encode('utf-8')
10 page = opener.open(url, data).read()
11 page = page.decode('utf-8')
12 return page

Python3中urllib模块的使用的更多相关文章

  1. Python2和Python3中urllib库中urlencode的使用注意事项

    前言 在Python中,我们通常使用urllib中的urlencode方法将字典编码,用于提交数据给url等操作,但是在Python2和Python3中urllib模块中所提供的urlencode的包 ...

  2. Python3:urllib模块的使用

    Python3:urllib模块的使用1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=N ...

  3. Python3中正则模块re.compile、re.match及re.search函数用法详解

    Python3中正则模块re.compile.re.match及re.search函数用法 re模块 re.compile.re.match. re.search 正则匹配的时候,第一个字符是 r,表 ...

  4. python3中urllib库的request模块详解

    刚刚接触爬虫,基础的东西得时时回顾才行,这么全面的帖子无论如何也得厚着脸皮转过来啊! 原帖地址:https://www.2cto.com/kf/201801/714859.html 什么是 Urlli ...

  5. 常见的爬虫分析库(1)-Python3中Urllib库基本使用

    原文来自:https://www.cnblogs.com/0bug/p/8893677.html 什么是Urllib? Python内置的HTTP请求库 urllib.request          ...

  6. Python3中Urllib库基本使用

    什么是Urllib? Python内置的HTTP请求库 urllib.request          请求模块 urllib.error              异常处理模块 urllib.par ...

  7. python3中urllib的基本使用

    urllib 在python3中,urllib和urllib2进行了合并,现在只有一个urllib模块,urllib和urllib2的中的内容整合进了urllib.request,urlparse整合 ...

  8. python3 中mlpy模块安装 出现 failed with error code 1的决绝办法(其他模块也可用本方法)

    在python3 中安装其它模块时经常出现 failed with error code 1等状况,使的安装无法进行.而解决这个问题又非常麻烦. 接下来以mlpy为例,介绍一种解决此类安装问题的办法. ...

  9. Python3中urllib详细使用方法(header,代理,超时,认证,异常处理)

    urllib是python的一个获取url(Uniform Resource Locators,统一资源定址器)了,我们可以利用它来抓取远程的数据进行保存哦,下面整理了一些关于urllib使用中的一些 ...

随机推荐

  1. JS全选反选功能

    总选框:<input type="checkbox" class="all" name="all"> 子选框: <inpu ...

  2. shiro认证登录实现

    准备工作: 在web.xml中配置shiro核心过滤器 在spring配置文件中提供核心过滤器运行所需要的辅助bean对象,在对象内注入安全管理器 拦截认证 配置三个url 拦截除了登录页面以及认证a ...

  3. asp.net无限递归

    private void button1_Click(object sender, EventArgs e) { DialogResult dialogResult = folderBrowserDi ...

  4. Oracle VM Virtual 安装 ubuntu 后设置全屏

    按照正常流程在vm中安装了ubuntu之后,发现ubuntu系统无法全屏显示,解决途径如下: 1.在vm中点击设置 2.选择“安装增强功能” 3.正常情况下,我们可以在桌面看到一个光盘图标(文件名:V ...

  5. zabbix监控实战<1>

    第一章 监控家族 1.1 为什么选择监控? 因为在一个IT集群中或者是一个大环境中,包括各种硬件设备.软件设备等系统的构成也是极其复杂的. 多种应用构成负载的IT业务系统,保证这些资源的正常运转,是一 ...

  6. 查看Python、flask 版本

    查看Django版本检查是否安装成功,可以在dos下查看Django版本. 1.输入python 2.输入import django3.输入django.get_version() 查看flask版本 ...

  7. Python记录wsgi

    类实现wsgi app from wsgiref.util import setup_testing_defaults from wsgiref.simple_server import make_s ...

  8. 解决Linux 环境 GLIBCXX_3.4.15' not found问题

    升级Centos系统之后,运行filezilla时,出现如下错误的提示信息: ./filezilla: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15 ...

  9. 【转】Powershell与jenkins集成部署的运用(powershell运用)

    powershell简介: 远程管理采用的一种新的通信协议,Web Services for Management,简称WS-MAN它通过http或者https进行工作,WS-WAN的实现主要基于一个 ...

  10. 在sparkStreaming实时存储时的问题

    1.实时插入mysql时遇到的问题,使用的updateStaeBykey有状态的算子 必须设置checkpoint  如果报错直接删掉checkpoint 在创建的时候自己保存偏移量即可 再次启动时读 ...