基础篇-Python的urllib库

news/2024/7/19 11:53:35 标签: python, 爬虫

urllib是Python自带的标准库,无需安装,直接可以用。
提供了如下功能:

  • 网页请求
  • 响应获取
  • 代理和cookie设置
  • 异常处理
  • URL解析

爬虫所需要的功能,基本上在urllib中都能找到,学习这个标准库,可以更加深入的理解后面更加便利的requests库。

urllib库

urlopen 语法

urllib.request.urlopen(url,data=None,[timeout,]*,cafile=None,capath=None,cadefault=False,context=None)
#url:访问的网址
#data:额外的数据,如header,form data

用法

# request:GET
import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))

# request: POST
# http测试:http://httpbin.org/
import urllib.parse
import urllib.request
data = bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post',data=data)
print(response.read())

# 超时设置
import urllib.request
response = urllib.request.urlopen('http://httpbin.org/get',timeout=1)
print(response.read())

import socket
import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIME OUT')

响应

# 响应类型
import urllib.open
response = urllib.request.urlopen('https:///www.python.org')
print(type(response))
# 状态码, 响应头
import urllib.request
response = urllib.request.urlopen('https://www.python.org')
print(response.status)
print(response.getheaders())
print(response.getheader('Server'))

Request

声明一个request对象,该对象可以包括header等信息,然后用urlopen打开。

# 简单例子
import urllib.request
request = urllib.request.Requests('https://python.org')
response = urllib.request.urlopen(request)
print(response.read().decode('utf-8'))

# 增加header
from urllib import request, parse
url = 'http://httpbin.org/post'
headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36'
    'Host':'httpbin.org'
}
# 构造POST表格
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')
# 或者随后增加header
from urllib import request, parse
url = 'http://httpbin.org/post'
dict = {
    'name':'Germey'
}
req = request.Request(url=url,data=data,method='POST')
req.add_hader('User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36')
response = request.urlopen(req)
print(response.read().decode('utf-8'))

Handler:处理更加复杂的页面

官方说明
代理

import urllib.request
proxy_handler = urllib.request.ProxyHandler({
    'http':'http://127.0.0.1:9743'
    'https':'https://127.0.0.1.9743'
})
opener = urllib.request.build_openner(proxy_handler)
response = opener.open('http://www.baidu.com')
print(response.read())

Cookie:客户端用于记录用户身份,维持登录信息

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)

# 保存cooki为文本
import http.cookiejar, urllib.request
filename = "cookie.txt"
# 保存类型有很多种
## 类型1
cookie = http.cookiejar.MozillaCookieJar(filename)
## 类型2
cookie = http.cookiejar.LWPCookieJar(filename)

handler = urllib.request.HTTPCookieProcessor(cookie)
opener = urllib.request.build_opener(handler)
response = opener.open("http://www.baidu.com")

# 使用相应的方法读取
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")

异常处理

捕获异常,保证程序稳定运行

# 访问不存在的页面
from urllib import request, error
try:
    response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:
    print(e.reason)

# 先捕获子类错误
from urllib imort request, error
try:
    response = request.urlopen('http://cuiqingcai.com/index.htm')
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')
# 判断原因
import socket
import urllib.request
import urllib.error

try:
    response = urllib.request.urlopen('http://httpbin.org/get',timeout=0.1)
except urllib.error.URLError as e:
    if isinstance(e.reason,socket.timeout):
        print('TIME OUT')

URL解析

主要是一个工具模块,可用于为爬虫提供URL。

urlparse:拆分URL

urlib.parse.urlparse(urlstring,scheme='', allow_fragments=True)
# scheme: 协议类型
# 是否忽略’#‘部分

举个例子

from urllib import urlparse
result = urlparse("https://edu.hellobi.com/course/157/play/lesson/2580")
result
##ParseResult(scheme='https', netloc='edu.hellobi.com', path='/course/157/play/lesson/2580', params='', query='', fragment='')

urlunparse:拼接URL,为urlparse的反向操作

from urllib.parse import urlunparse
data = ['http','www.baidu.com','index.html','user','a=6','comment']
print(urlunparse(data))

urljoin:拼接两个URL

img_eee662d4aba8baee47631fe1ad5c4f7c.png
urljoin

urlencode:字典对象转换成GET请求对象

from urllib.parse import urlencode
params = {
    'name':'germey',
    'age': 22
}
base_url = 'http://www.baidu.com?'
url = base_url + urlencode(params)
print(url)

最后还有一个robotparse,解析网站允许爬取的部分。


http://www.niftyadmin.cn/n/1446296.html

相关文章

常见网吧计算机系统故障的解决方法(转)

一、在Windows下经常出现蓝屏故障出现此类故障的表现方式多样,有时在Windows启动时出现,有时在Windows下运行一些软件时出现,出现此类故障一般是由于用户操作不当促使Windows系统损坏造成,此类现象具体表现在以安全模式引导时不能…

hdu 5100 Chessboard(数学)

题目链接:hdu 5100 Chessboard 题目大意:给定一个N∗N的棋盘,用1∗K的木块,问最多能铺满多少单位位置。 解题思路:这题貌似有公式,表示根本不知道公式啊。用递归写的,无非两种情况,一…

SQL2005其中三个版本的比较(转)

SQL2005 分五个版本,如下所列,1.Enterprise(企业版), 2.Development(开发版),3.Workgroup,(工作群版)4.Standard,(标准版)5.Express.(嗯,估且就叫它简易版吧)这几个版本,我们究竟应该使用哪一版呢﹖这是许多初学SQL2005的人最常问…

Greenplum助医疗大数据从“奢侈品”走向常态化

增加医疗大数据平台的便捷功能服务,推动医疗大数据的常态化应用。 近年来,大数据产业发展如火如荼。不过,在医疗领域,医疗大数据平台在不少医院心目中还是曲高和寡的“奢侈品”。 2019年5月,中国医院协会信息专业委员会…

希捷1TB硬盘正式发布

随着全球范围内数字内容的迅猛增长,希捷科技公司(NYSE:STX)日前宣布为各种企业和台式电脑应用提供行业领先的集容量、性能、可靠性为一体的1TB硬盘。数字内容在家庭和办公室的爆炸性增长带动了市场对大容量硬盘的迫切需求。企业和消费者不断制造和消费着惊人的数字内…

RH134 UNIT5

使用逻辑卷管理器管理灵活存储一.LVM定义物理分区或磁盘是 LVM 的第一构建块。这些可以是分区、完整磁盘、 RAID 集或 SAN 磁盘 物理卷是 LVM 所使用的基础 “ 物理 ” 存储。这通常是块设备 ,例如分区或完整磁盘。设备必须初 始 化为 LVM 物理卷 , 才能与 LVM 结合使用 …

hdu 5101 Select(树状数组)

题目链接:hdu5101 Select 题目大意:N和K,给定若干组数,要从从不同组中选出连个数和大于K,问说有多少种组成方案。 解题思路:树状数组维护,将所有的数离散化掉对应成树状数组的下标,每…

用Access 2000进行班级管理(转)

教师的责任与义务从未因为时代的变迁而削弱过,教育本身的特殊性使教师成为知识的传播者和人类灵魂的塑造者。而作为中小学的班主任教师,需要担负的责任却远比这要实际得多,也繁琐得多。庞杂的学生基本信息需要管理和上报,班级日常…