Python 爬虫常用的库
一、常用库
1、requests 做请求的时候用到。
requests.get("url")
2、selenium 自动化会用到。
3、lxml
4、beautifulsoup
5、pyquery 网页解析库 说是比beautiful 好用,语法和jquery非常像。
6、pymysql 存储库。操作mysql数据的。
7、pymongo 操作MongoDB 数据库。
8、redis 非关系型数据库。
9、jupyter 在线记事本。
二、什么是Urllib
Python内置的Http请求库
urllib.request 请求模块 模拟浏览器
urllib.error 异常处理模块
urllib.parse url解析模块 工具模块,如:拆分、合并
urllib.robotparser robots.txt 解析模块
2和3的区别
Python2
import urllib2
response = urllib2.urlopen('http://www.baidu.com');
Python3
import urllib.request
response =urllib.request.urlopen('http://www.baidu.com');
用法:
urlOpen 发送请求给服务器。
urllib.request.urlopen(url,data=None[参数],[timeout,]*,cafile=None,capath=None,cadefault=false,context=None)
例子:
例子1:
import urllib.requests
response=urllib.reqeust.urlopen('http://www.baidu.com')
print(response.read().decode('utf-8'))
例子2:
import urllib.request
import urllib.parse
data=bytes(urllib.parse.urlencode({'word':'hello'}),encoding='utf8')
response=urllib.reqeust.urlopen('http://httpbin.org/post',data=data)
print(response.read())
注:加data就是post发送,不加就是以get发送。
例子3:
超时测试
import urllib.request
response =urllib.request.urlopen('http://httpbin.org/get',timeout=1)
print(response.read())
-----正常
import socket
import urllib.reqeust
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')
这是就是输出 TIME OUT
响应
响应类型
import urllib.request
response=urllib.request.urlopen('https://www.python.org')
print(type(response))
输出:print(type(response))

状态码、响应头
import urllib.request
response = urllib.request.urlopen('http://www.python.org')
print(response.status) // 正确返回200
print(response.getheaders()) //返回请求头
print(response.getheader('Server'))
三、Request 可以添加headers
import urllib.request
request=urllib.request.Request('https://python.org')
response=urllib.request.urlopen(request)
print(response.read().decode('utf-8'))
例子:
from urllib import request,parse
url='http://httpbin.org/post'
headers={
}
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'))
四、代理
import urllib.request
proxy_handler =urllib.request.ProxyHandler({
'http':'http://127.0.0.1:9743',
'https':'http://127.0.0.1:9743',
})
opener =urllib.request.build_opener(proxy_handler)
response= opener.open('http://httpbin.org/get')
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)
第一种保存cookie方式
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方式
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
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 reqeust,error
try:
response =request.urlopen('http://cuiqingcai.com/index.htm')
except error.URLError as e:
print(e.reason) //url异常捕获
例子2:
from urllib import reqeust,error
try:
response =request.urlopen('http://cuiqingcai.com/index.htm')
except error.HTTPError as e:
print(e.reason,e.code,e.headers,sep='\n') //url异常捕获
except error.URLError as e:
print(e.reason)
else:
print('Request Successfully')
7、URL解析
urlparse //url 拆分
urllib.parse.urlparse(urlstring,scheme='',allow_fragments=True)
例子:
from urllib.parse import urlparse //url 拆分
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment')
print(type(result),result)
结果:

例子2:
from urllib.parse import urlparse //没有http
result = urlparse('www.baidu.com/index.html;user?id=5#comment',scheme='https')
print(result)

例子3:
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment',scheme='https')
print(result)

例子4:
from urllib.parse import urlparse
result = urlparse('http://www.baidu.com/index.html;user?id=5#comment',allow_fragments=False)
print(result)

例子5:
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))

urljoin
from urllib.parse import urljoin
print(urljoin('http://www.baidu.com','FAQ.html'))

后面覆盖前面的
urlencode
from urllib.parse import urlencode
params={
'name':'gemey',
'age':22
}
base_url='http//www.baidu.com?'
url = base_url+urlencode(params)
print(url)
http://www.baidu.com?name=gemey&age=22
Python 爬虫常用的库的更多相关文章
- python爬虫常用第三方库
这个列表包含与网页抓取和数据处理的Python库 网络 通用 urllib -网络库(stdlib). requests -网络库. grab – 网络库(基于pycurl). pycurl – 网络 ...
- python爬虫常用的库
1,请求:requests requests.get(url, headers) requests.post(url, data=data, files=files) urllib模块: Py ...
- Python爬虫之selenium库使用详解
Python爬虫之selenium库使用详解 本章内容如下: 什么是Selenium selenium基本使用 声明浏览器对象 访问页面 查找元素 多个元素查找 元素交互操作 交互动作 执行JavaS ...
- python爬虫之urllib库(三)
python爬虫之urllib库(三) urllib库 访问网页都是通过HTTP协议进行的,而HTTP协议是一种无状态的协议,即记不住来者何人.举个栗子,天猫上买东西,需要先登录天猫账号进入主页,再去 ...
- python爬虫之urllib库(二)
python爬虫之urllib库(二) urllib库 超时设置 网页长时间无法响应的,系统会判断网页超时,无法打开网页.对于爬虫而言,我们作为网页的访问者,不能一直等着服务器给我们返回错误信息,耗费 ...
- python爬虫之urllib库(一)
python爬虫之urllib库(一) urllib库 urllib库是python提供的一种用于操作URL的模块,python2中是urllib和urllib2两个库文件,python3中整合在了u ...
- python爬虫(四)_urllib2库的基本使用
本篇我们将开始学习如何进行网页抓取,更多内容请参考:python学习指南 urllib2库的基本使用 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地.在Python中有很 ...
- python爬虫之requests库
在python爬虫中,要想获取url的原网页,就要用到众所周知的强大好用的requests库,在2018年python文档年度总结中,requests库使用率排行第一,接下来就开始简单的使用reque ...
- Python爬虫常用之PyQuery
PyQuery是解析页面常用的库.是python对jquery的封装.下面是一份解析基本页面的代码.后期用到复杂或者实用的方式再增加. from pyquery import PyQuery as p ...
随机推荐
- SpringBoot整合redis哨兵主从服务
前提环境: 主从配置 http://www.cnblogs.com/zwcry/p/9046207.html 哨兵配置 https://www.cnblogs.com/zwcry/p/9134721. ...
- 自学Java第五周的总结
在这周里我在我要自学网上观看视频学习了有关java的基础知识,课程主要介绍JavaSE,这是整个Java体系的基础:课程将由浅入深,并结合案例进行讲解,在那里我将自己已学的知识进行了巩固,并由学习到了 ...
- Kali linux apt-get update 失败,无release……(最有效)
设置源 编辑 /etc/apt/sources.list nano /etc/apt/sources.list 清空文件内所有内容后添加 deb http://mirrors.ustc.edu.cn/ ...
- Python进阶【第九篇】装饰器
什么是装饰器 装饰器本身就是函数,并且为其他函数添加附加功能 装饰器的原则:1.不修改被装饰对象的源代码 2.不修改被装饰对象的调用方式装饰器=高阶函数+函数嵌套+闭包 # res=timmer(t ...
- shell =~ 引发的思考
=~不是按位取反 1.[[]] if [[]]中引用变量不用加 双引号(")了,而if[]中变量必须加双引号,如if[ -n "$test" ],不然一些特殊的地方,会出 ...
- 【react】兄弟组件的通信方式,传统非redux
很多用过redux开发的朋友们都知道,一般兄弟组件通信可以使用redux. redux也是近期在挤时间学习中.可能也不是很懂,说不定是有错误的理解,若有.现在虽然自己搭建了一个react+router ...
- 线程池demo
package test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callabl ...
- javax.servlet.ServletException: Servlet.init() for servlet springmvc threw exception
type Exception report message Servlet.init() for servlet springmvc threw exception description The s ...
- Zookeeper本地模式安装
本地模式安装部署 1.安装前准备 (1)安装Jdk (2)拷贝Zookeeper安装包到Linux系统下 (3)解压到指定目录 tar -zxvf zookeeper-3.4.10.tar.gz -C ...
- ThirdAPI
//public class ThirdAPI //{ // [DllImport("ThirdAPI.dll")] // public static extern int Ini ...