爬虫(二):Urllib库详解
什么是Urllib:
python内置的HTTP请求库
urllib.request : 请求模块
urllib.error : 异常处理模块
urllib.parse: url解析模块
urllib.robotparser : robots.txt解析模块
GET请求方式
POST请求方式
超时timeout,异常处理
响应类型(响应码,响应头...)
POST请求添加Headers
代理方法
cookie添加 读取
---------- parse 包下 -----------
urlparse 解析网址
urlunparse 拼接网址
urlencode GET参数化(比较有用)
python3:
urlopen
# urllib参数
urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=False, context=None)
# url post数据 超时 #############################
import urllib.request # GET方式(不加data)
response = urllib.request.urlopen('http://www.baidu.com') # 请求数据
print(response.read().decode('utf-8')) # 转换为字符串编码,read()得到的是byte格式的
#############################
import urllib.parse
import urllib.request # POST方式(加data)
data = bytes(urllib.parse.urlencode({'word': 'hello'}), encoding='utf8')
response = urllib.request.urlopen('http://httpbin.org/post', data=data) # http://httpbin.org/post 用来做HTTP测试的网址
print(response.read())
#############################
import urllib.request #超时设置
response = urllib.request.urlopen('http://httpbin.org/get', timeout=1)
print(response.read())
##############################
响应
# 响应类型
import urllib.request response = urllib.request.urlopen('https://www.python.org')
print(type(response)) #<class 'http.client.HTTPResponse'> #############################
# 状态码、响应头
import urllib.request response = urllib.request.urlopen('https://www.python.org')
print(response.status) #获取状态码
print(response.getheaders()) # 获取响应头
print(response.getheader('Server')) # 响应的服务
#############################
import urllib.request
#获取响应内容
response = urllib.request.urlopen('https://www.python.org')
print(response.read().decode('utf-8')) # read() 获取bytes类型
Request
# 加入headers,发送一个POST请求
from urllib import request, parse url = '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'))
Handler
# 添加代理
import urllib.request proxy_handler = urllib.request.ProxyHandler({ # 代理设置
'http': 'http://127.0.0.1:9743',
'https': 'https://127.0.0.1:9742'
})
opener = urllib.request.build_opener(proxy_handler)
response = opener.open('http://httpbin.org/get')
print(response.read())
Cookie
import http.cookiejar, urllib.request # 获取cookies
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保存为txt文件
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) #############################
# 读取cookie文件
import http.cookiejar, urllib.request
# 用哪种格式存cookies,就用哪种方法读取
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
from urllib import request, error
try:
response = request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:
print(e.reason) #############################
# 异常处理2
from urllib import 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')
#############################
# 异常处理3
import socket
import urllib.request
import urllib.error try:
response = urllib.request.urlopen('https://www.baidu.com', timeout=0.01)
except urllib.error.URLError as e:
print(type(e.reason))
if isinstance(e.reason, socket.timeout):
print('TIME OUT')
URL解析
# 一个参数
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result), result) ##########################
# 指定协议, 如果没有取https, 有就用url带的
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment', scheme='https') # 指定协议类型
print(result) ##########################
# allow_fragments=False 一般不会用,把锚链接部分移动到参数(没有参数在往前移动#XXXX)
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html#comment', allow_fragments=False)
print(result)
urlunparse
from urllib.parse import urlunparse
# 拼接网站
data = ['http', 'www.baidu.com', 'index.html', 'user', 'a=6', 'comment']
print(urlunparse(data)) #http://www.baidu.com/index.html;user?a=6#comment
urljoin
from urllib.parse import urljoin
# 拼接
print(urljoin('http://www.baidu.com', 'Faq.html'))
# 以第二个位基准
print(urljoin('http://www.baidu.com', 'https://www.baidu.com/aaa'))
# 拼接
print(urljoin('http://www.baidu.com', '?a=1'))
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) # http://www.baidu.com?name=germey&age=22
爬虫(二):Urllib库详解的更多相关文章
- Python爬虫系列-Urllib库详解
Urllib库详解 Python内置的Http请求库: * urllib.request 请求模块 * urllib.error 异常处理模块 * urllib.parse url解析模块 * url ...
- 爬虫入门之urllib库详解(二)
爬虫入门之urllib库详解(二) 1 urllib模块 urllib模块是一个运用于URL的包 urllib.request用于访问和读取URLS urllib.error包括了所有urllib.r ...
- Python爬虫:requests 库详解,cookie操作与实战
原文 第三方库 requests是基于urllib编写的.比urllib库强大,非常适合爬虫的编写. 安装: pip install requests 简单的爬百度首页的例子: response.te ...
- Python爬虫之urllib.parse详解
Python爬虫之urllib.parse 转载地址 Python 中的 urllib.parse 模块提供了很多解析和组建 URL 的函数. 解析url 解析url( urlparse() ) ur ...
- python爬虫知识点总结(三)urllib库详解
一.什么是Urllib? 官方学习文档:https://docs.python.org/3/library/urllib.html 廖雪峰的网站:https://www.liaoxuefeng.com ...
- 爬虫--Urllib库详解
1.什么是Urllib? 2.相比Python2的变化 3.用法讲解 (1)urlopen urlllb.request.urlopen(url,data=None[timeout,],cahle=N ...
- urllib库详解 --Python3
相关:urllib是python内置的http请求库,本文介绍urllib三个模块:请求模块urllib.request.异常处理模块urllib.error.url解析模块urllib.parse. ...
- 爬虫学习--Requests库详解 Day2
什么是Requests Requests是用python语言编写,基于urllib,采用Apache2 licensed开源协议的HTTP库,它比urllib更加方便,可以节约我们大量的工作,完全满足 ...
- Python爬虫系列-Requests库详解
Requests基于urllib,比urllib更加方便,可以节约我们大量的工作,完全满足HTTP测试需求. 实例引入 import requests response = requests.get( ...
随机推荐
- 2019牛客多校八 H. How Many Schemes (AC自动机,树链剖分)
大意: 给定树, 每条边有一个字符集合, 给定$m$个模式串, $q$个询问$(u,v)$, 对于路径$(u,v)$中的所有边, 每条边从对应字符集合中取一个字符, 得到一个串$s$, 求$s$至少包 ...
- hoj 棋盘问题 状压入个门
大概题意是:有一个n*m的棋盘,在这个棋盘里边放k个旗子,要求每一行每一列都不能存在一对旗子相邻,问最后总共的方案数. 我们先来考虑个简单的,假如说只有一行,要求在这一行里边填充k个旗子,要求任意两个 ...
- 既有设计模式的lambda重构
设计模式的博客要有模式的定义,UML类图,代码实现和模式的优缺点, 策略模式 工厂模式 模版方法 观察者模式 责任链模式 1 策略模式:定义了一组算法,并将每一个算法封装起来,使它们每一个之间可以相互 ...
- css 基础入门
CSS 概述 为了让网页元素的样式更加丰富,也为了让网页的内容和样式能拆分开,css 由此而生,css 是 Cascading Style Sheets 的字母缩写,意思是层叠样式表,有了 css,h ...
- 详解Spring Cloud中Hystrix 线程隔离导致ThreadLocal数据丢失
在Spring Cloud中我们用Hystrix来实现断路器,Zuul中默认是用信号量(Hystrix默认是线程)来进行隔离的,我们可以通过配置使用线程方式隔离. 在使用线程隔离的时候,有个问题是必须 ...
- Git撤回已经推送(push)至远程仓库提交(commit)的版本
背景 所以,经常会遇到已经提交远程仓库,但是又不是我想要的版本,要撤下来. 回退版本一般使用git reset,又分为: # 不删除工作空间改动代码,撤销commit,不撤销git add . git ...
- TypeScript入门一:配置TS工作环境
配置手动编译TS文件工作环境 配置webpack自动化打包编译工作环境(后面补充) 一.TypeScript入门学习引言 进入主题之前,首先说明这个系列的博客是我刚刚接触TypeScript的学习笔记 ...
- UI5-技术篇-SAPUI5创建自定义控件
转载:https://www.nabisoft.com/tutorials/sapui5/creating-custom-controls-in-sapui5 https://sapui5.h ...
- visualSVN server 安装成功,但是无法连接,url打不开
转自:https://www.oschina.net/question/878142_91825 点击开始–>程序->VisualSVN–>VisuaSVN Server Manag ...
- python小实例——tkinter实战(计算器)
一.完美计算器实验一 import tkinter import math import tkinter.messagebox class calculator: #界面布局方法 def __init ...