原文来自:https://www.cnblogs.com/0bug/p/8893677.html

什么是Urllib?

Python内置的HTTP请求库

urllib.request          请求模块

urllib.error              异常处理模块

urllib.parse             url解析模块

urllib.robotparser    robots.txt解析模块

相比Python的变化

Python2中的urllib2在Python3中被统一移动到了urllib.request中

python2

import urllib2

response = urllib2.urlopen('http://www.cnblogs.com/0bug')

Python3

import urllib.request

response = urllib.request.urlopen('http://www.cnblogs.com/0bug/')

urlopen()

不加data是以GET方式发送,加data是以POST发送

1
2
3
4
5
import urllib.request
 
response = urllib.request.urlopen('http://www.cnblogs.com/0bug')
html = response.read().decode('utf-8')
print(html)
 结果

加data发送POST请求

1
2
3
4
5
6
import urllib.parse
import urllib.request
 
data = bytes(urllib.parse.urlencode({'hello''0bug'}), encoding='utf-8')
response = urllib.request.urlopen('http://httpbin.org/post', data=data)
print(response.read())

timeout超时间

1
2
3
4
import urllib.request
 
response = urllib.request.urlopen('http://www.cnblogs.com/0bug', timeout=0.01)
print(response.read())
1
2
3
4
5
6
7
8
import urllib.request
import socket
import urllib.error
try:
    response = urllib.request.urlopen('http://www.cnblogs.com/0bug', timeout=0.01)
except urllib.error.URLError as  e:
    if isinstance(e.reason,socket.timeout):
        print('请求超时')

响应

1.响应类型

1
2
3
4
import urllib.request
 
response = urllib.request.urlopen('http://www.cnblogs.com/0bug')
print(type(response))

2.状态码、响应头

1
2
3
4
5
6
import urllib.request
 
response = urllib.request.urlopen('http://www.cnblogs.com/0bug')
print(response.status)
print(response.getheaders())
print(response.getheader('Content-Type'))

3.响应体

响应体是字节流,需要decode('utf-8')

1
2
3
4
5
import urllib.request
 
response = urllib.request.urlopen('http://www.cnblogs.com/0bug')
html = response.read().decode('utf-8')
print(html)

Request

1
2
3
4
5
import urllib.request
 
request = urllib.request.Request('http://www.cnblogs.com/0bug')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

添加请求头信息

1
2
3
4
5
6
7
8
9
10
11
12
from urllib import request, parse
 
url = 'http://httpbin.org/post'
headers = {
    'User-Agent''Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36',
    'Host''httpbin.org'
}
dic = {'name''0bug'}
data = bytes(parse.urlencode(dic), encoding='utf-8')
req = request.Request(url=url, data=data, headers=headers, method='POST')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

add_header

1
2
3
4
5
6
7
8
9
10
from urllib import request, parse
 
url = 'http://httpbin.org/post'
dic = {'name''0bug'}
data = bytes(parse.urlencode(dic), encoding='utf-8')
req = request.Request(url=url, data=data, method='POST')
req.add_header('User-Agent',
               'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

Handler

代理:

1
2
3
4
5
6
7
8
9
import urllib.request
 
proxy_handler = urllib.request.ProxyHandler({
    'http''http代理',
    'https''https代理'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://www.cnblogs.com/0bug')
print(response.read())

Cookie

1
2
3
4
5
6
7
8
import http.cookiejar, urllib.request
 
cookie = http.cookiejar.CookieJar()
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
for item in cookie:
    print(item.name + "=" + item.value)

Cookie保存为文件

1
2
3
4
5
6
7
8
import http.cookiejar, urllib.request
 
filename = 'cookie.txt'
cookie = http.cookiejar.MozillaCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)
 cookie.txt

另一种方式存

1
2
3
4
5
6
7
8
import http.cookiejar, urllib.request
 
filename = 'cookie.txt'
cookie = http.cookiejar.LWPCookieJar(filename)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
cookie.save(ignore_discard=True, ignore_expires=True)

用什么格式的存就应该用什么格式的读

1
2
3
4
5
6
7
8
import http.cookiejar, urllib.request
 
cookie = http.cookiejar.LWPCookieJar()
cookie.load('cookie.txt', ignore_discard=True, ignore_expires=True)
handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open('http://www.baidu.com')
print(response.read().decode('utf-8'))

异常处理

1
2
3
4
5
6
from urllib import request, error
 
try:
    response = request.urlopen('http://www.cnblogs.com/0bug/xxxx')
except error.URLError as e:
    print(e.reason)
1
2
3
4
5
6
7
8
9
10
from urllib import request, error
 
try:
    response = request.urlopen('http://www.cnblogs.com/0bug/xxxx')
except error.HTTPError as e:
    print(e.reason, e.code, e.headers, sep='\n')
except error.URLError as e:
    print(e.reason)
else:
    print('Request Successfully')
1
2
3
4
5
6
7
8
9
10
import socket
import urllib.request
import urllib.error
 
try:
    response = urllib.request.urlopen('http://www.cnblogs.com/0bug/xxxx', timeout=0.001)
except urllib.error.URLError as e:
    print(type(e.reason))
    if isinstance(e.reason, socket.timeout):
        print('请求超时')

URL解析

1
2
3
4
5
from urllib.parse import urlparse
 
result = urlparse('www.baidu.com/index.html;user?id=5#comment')
print(type(result))
print(result)
1
2
3
4
from urllib.parse import urlparse
 
result = urlparse('www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result)
1
2
3
4
from urllib.parse import urlparse
 
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', scheme='https')
print(result)
1
2
3
4
from urllib.parse import urlparse
 
result = urlparse('http://www.badiu.com/index.html;user?id=5#comment', allow_fragments=False)
print(result)
1
2
3
4
from urllib.parse import urlparse
 
result = urlparse('http://www.badiu.com/index.html#comment', allow_fragments=False)
print(result)

urlunparse

1
2
3
4
from urllib.parse import urlunparse
 
data = ['http''www.baidu.com''index.html''user''id=6''comment']
print(urlunparse(data))

urljoin

1
2
3
4
5
6
7
8
9
10
from urllib.parse import urljoin
 
print(urljoin('http://www.baidu.com''ABC.html'))
print(urljoin('http://www.baidu.com''https://www.cnblogs.com/0bug'))
print(urljoin('http://www.baidu.com/0bug''https://www.cnblogs.com/0bug'))
print(urljoin('http://www.baidu.com/0bug''https://www.cnblogs.com/0bug?q=2'))
print(urljoin('http://www.baidu.com/0bug?q=2''https://www.cnblogs.com/0bug'))
print(urljoin('http://www.baidu.com''?q=2#comment'))
print(urljoin('www.baidu.com''?q=2#comment'))
print(urljoin('www.baidu.com#comment''?q=2'))

urlencode

1
2
3
4
5
6
7
8
9
from urllib.parse import urlencode
 
params = {
    'name''0bug',
    'age': 25
}
base_url = 'http://www.badiu.com?'
url = base_url + urlencode(params)
print(url)

常见的爬虫分析库(1)-Python3中Urllib库基本使用的更多相关文章

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

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

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

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

  3. Python3中Urllib库基本使用

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

  4. 爬虫中urllib库

    一.urllib库 urllib是Python自带的一个用于爬虫的库,其主要作用就是可以通过代码模拟浏览器发送请求.其常被用到的子模块在Python3中的为urllib.request和urllib. ...

  5. 对python3中pathlib库的Path类的使用详解

    原文连接   https://www.jb51.net/article/148789.htm 1.调用库 ? 1 from pathlib import 2.创建Path对象 ? 1 2 3 4 5 ...

  6. Python3中urllib使用介绍

    Py2.x: Urllib库 Urllin2库 Py3.x: Urllib库 变化: 在Pytho2.x中使用import urllib2——-对应的,在Python3.x中会使用import url ...

  7. Python3中urllib使用与源代码

    Py2.x: Urllib库 Urllin2库 Py3.x: Urllib库 变化: 在Pytho2.x中使用import urllib2---对应的,在Python3.x中会使用import url ...

  8. Python爬虫入门(3-4):Urllib库的高级用法

    1.分分钟扒一个网页下来 怎样扒网页呢?其实就是根据URL来获取它的网页信息,虽然我们在浏览器中看到的是一幅幅优美的画面,但是其实是由浏览器解释才呈现出来的,实质它 是一段HTML代码,加 JS.CS ...

  9. Python爬虫实战(一) 使用urllib库爬取拉勾网数据

    本笔记写于2020年2月4日.Python版本为3.7.4,编辑器是VS code 主要参考资料有: B站视频av44518113 Python官方文档 PS:如果笔记中有任何错误,欢迎在评论中指出, ...

随机推荐

  1. Tesseract识别图片提取文字&字库训练

    文中测试了3.0和4.0两个版本.发现3.0识别效率不准确,需要训练词库.4.0识别效率就比较高了,而且支持结果生成pdf.txt等格式.所以推荐使用4.0版本. 这个工具可以用在爬虫的时候获取验证码 ...

  2. 2018 Multi-University Training Contest 1 杭电多校第一场

    抱着可能杭电的多校1比牛客的多校1更恐怖的想法 看到三道签到题 幸福的都快哭出来了好吗 1001  Maximum Multiple(hdoj 6298) 链接:http://acm.hdu.edu. ...

  3. k64 datasheet学习笔记12---System Integration Module (SIM)

    1.前言 Features of the SIM include: System clocking configuration(1)System clock divide values(2) Arch ...

  4. 从运维角度来分析mysql数据库优化的一些关键点【转】

    概述 一个成熟的数据库架构并不是一开始设计就具备高可用.高伸缩等特性的,它是随着用户量的增加,基础架构才逐渐完善. 1.数据库表设计 项目立项后,开发部根据产品部需求开发项目,开发工程师工作其中一部分 ...

  5. python标准库之argparse

    argparse的使用 argparse 是 Python 内置的一个用于命令项选项与参数解析的模块,通过在程序中定义好我们需要的参数,argparse 将会从 sys.argv 中解析出这些参数,并 ...

  6. liunx之Centos6.8杀毒软件的安装

    作者:邓聪聪 为了防止服务器中病毒,安装了类似与Windowns的杀毒软件Clanav,过程如下 首先下载clamav的软件包,官方下载地址为http://www.clamav.net/downloa ...

  7. ASP.NET WEBAPI 使用Swagger生成API文档

    一.安装 新建一个没有身份验证的mvc项目 - SwaggerMvc5Demo,然后添加一个名为Remote(自定义)且包含基础读写(不想手写)的ApiController   开源地址:https: ...

  8. K-query SPOJ - KQUERY 离线 线段树/树状数组 区间大于K的个数

    题意: 给一个数列,一些询问,问你区间$[l.r]$大于$K$的个数 题解: 又一个"人尽皆知傻逼题"? 我们用一个01序列表示当前询问时,该位置的数字是否对答案有贡献, 显然,对 ...

  9. <TCP/IP>记一次关于IP地址和MAC物理地址的思考

    是的,从3月6日第一次上计算机网络课起,我还是今天第一次对这本书里讲的知识点有了自己的疑问..之前看书就是 嗯嗯这好像很有道理,嗯嗯也许再多看几章就知道它在讲什么了.. 不过今天已经自学到了网络层了, ...

  10. vue中更换.ico图标报错路径找不到图片

    问题描述: vue项目中,想要更换.ico图片,更换完成后刷新页面报错,找不到路径. 解决: 更换完图片,重新启动下vue项目(npm run dev)就可以啦~ 哈哈哈 补充知识: 网页title旁 ...