一、常用库

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={

    User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.75 Safari/537.36
    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'))

四、代理

  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 爬虫常用的库的更多相关文章

  1. python爬虫常用第三方库

    这个列表包含与网页抓取和数据处理的Python库 网络 通用 urllib -网络库(stdlib). requests -网络库. grab – 网络库(基于pycurl). pycurl – 网络 ...

  2. python爬虫常用的库

    1,请求:requests  requests.get(url, headers)  requests.post(url, data=data, files=files)  urllib模块:  Py ...

  3. Python爬虫之selenium库使用详解

    Python爬虫之selenium库使用详解 本章内容如下: 什么是Selenium selenium基本使用 声明浏览器对象 访问页面 查找元素 多个元素查找 元素交互操作 交互动作 执行JavaS ...

  4. python爬虫之urllib库(三)

    python爬虫之urllib库(三) urllib库 访问网页都是通过HTTP协议进行的,而HTTP协议是一种无状态的协议,即记不住来者何人.举个栗子,天猫上买东西,需要先登录天猫账号进入主页,再去 ...

  5. python爬虫之urllib库(二)

    python爬虫之urllib库(二) urllib库 超时设置 网页长时间无法响应的,系统会判断网页超时,无法打开网页.对于爬虫而言,我们作为网页的访问者,不能一直等着服务器给我们返回错误信息,耗费 ...

  6. python爬虫之urllib库(一)

    python爬虫之urllib库(一) urllib库 urllib库是python提供的一种用于操作URL的模块,python2中是urllib和urllib2两个库文件,python3中整合在了u ...

  7. python爬虫(四)_urllib2库的基本使用

    本篇我们将开始学习如何进行网页抓取,更多内容请参考:python学习指南 urllib2库的基本使用 所谓网页抓取,就是把URL地址中指定的网络资源从网络流中读取出来,保存到本地.在Python中有很 ...

  8. python爬虫之requests库

    在python爬虫中,要想获取url的原网页,就要用到众所周知的强大好用的requests库,在2018年python文档年度总结中,requests库使用率排行第一,接下来就开始简单的使用reque ...

  9. Python爬虫常用之PyQuery

    PyQuery是解析页面常用的库.是python对jquery的封装.下面是一份解析基本页面的代码.后期用到复杂或者实用的方式再增加. from pyquery import PyQuery as p ...

随机推荐

  1. XWIKI部署安装

    http://www.linuxidc.com/Linux/2016-08/134408.htm

  2. PNG文件格式详解

    源文件地址:https://blog.mythsman.com/2015/12/08/1/ 最近在看隐写术的时候经常需要研究图片文件的二进制文档格式,那么这就很有必要了解我们的图片文件究竟是如何保存的 ...

  3. 第一节 JavaScript概述

    第一节 JavaScript概述 JavaScript:其实就是对HTML+CSS静态页面进行样式修改,使其实现各种动态效果. 编写JS脚本基本步骤: 1. HTML+CSS静态布局: 2. 确定要修 ...

  4. K8S学习笔记之Kubernetes核心概念

    0x00  Kubernetes简介 Kubernetes(K8S)是Google开源的容器集群管理系统,其设计源于Google在容器编排方面积累的丰富经验,并结合社区创新的最佳实践. K8S在Doc ...

  5. php 版本号 整数化 mysql存储入库 比较大小【版本处理类,提供版本与数字互相转换】

    下载地址:https://download.csdn.net/download/a724008158/10659015

  6. php 获取网站根目录

    方法1(需自行调整根目录): define('BASE_PATH',str_replace('\\','/',realpath(dirname(__FILE__).'/'))."/" ...

  7. Golang生成区间随机整数

    package main import ( "fmt" "math/rand" "time" ) func main() { rand.Se ...

  8. spring boot @Scheduled未生效原因以及相关坑、及相对其他定时任务架构的优势

    在spring boot中,支持多种定时执行模式(cron, fixRate, fixDelay),在Application或者其他Autoconfig上增加@EnableScheduling注解开启 ...

  9. DevExpress GridControl使用方法总结2

    一.如何解决单击记录整行选中的问题 View->OptionsBehavior->EditorShowMode 设置为:Click 二.如何新增一条记录 (1).gridView.AddN ...

  10. Github网站加载不完全,响应超时,解决办法

    Github网站加载缓慢信息不全解决方法 Github是一个代码托管平台和开发者社区,开发者可以在Github上创建自己的开源项目并与其他开发者协作编码.毫不夸张地说,高效利用Github是一个优秀的 ...