一、常用库

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. Linux服务器---邮件服务器dovecot

    安装dovecot Dovecot是CentOS系统中著名的POP3/IMAP服务器实现.POP3/IMAP是从邮件服务器中读取邮件时使用的协议,POP3将邮件全部从服务器中拖取下来:IMAP则每次从 ...

  2. HDU 1207 汉诺塔II (递推)

    经典的汉诺塔问题经常作为一个递归的经典例题存在.可能有人并不知道汉诺塔问题的典故.汉诺塔来源于印度传说的一个故事,上帝创造世界时作了三根金刚石柱子,在一根柱子上从下往上按大小顺序摞着64片黄金圆盘.上 ...

  3. 如何通过命令行使用Wisdom RESTClient?

    Wisdom RESTClient V1.2版本开始支持命令行方式运行. 工具地址: https://github.com/Wisdom-Projects/rest-client 使用说明:java ...

  4. scrapy selenium 登陆zhihu

    # -*- coding: utf-8 -*- # 导入依赖包 import scrapy from selenium import webdriver import time import json ...

  5. python之内置函数与匿名函数

    一内置函数 # print(abs(-1)) # print(all([1,2,'a',None])) # print(all([])) #bool值为假的情况:None,空,0,False # # ...

  6. 【题解】Luogu P2073 送花

    原题传送门 这题需要用到Splay 我们用一棵splay维护金钱 考虑c<=1000000 我们珂以把每种价格现在对应的美丽值存在一个a数组中 这样讲有珂能不太清楚qaq,还是对着操作一个一个讲 ...

  7. nginx负载均衡fair方式分发

    fair采用的不是内建负载均衡使用的轮换的均衡算法,而是可以根据页面大小.加载时间长短智能的进行负载均衡. 这算是没有安装fair的情况 [root@localhost sbin]# ./nginx ...

  8. 【python39--面向对象组合】

    一.组合 定义:当几个对象是水平方向的时候,就应该考虑组合,当对象是纵向的时候用继承,组合就是用一个类把2个平级层次的类放在一起,然后实例化就可以了 #现在定义一个类,叫水池,水池里面有鱼和乌龟cla ...

  9. Dart语言快速学习上手(新手上路)

    Dart语言快速学习上手(新手上路) // 声明返回值 int add(int a, int b) { return a + b; } // 不声明返回值 add2(int a, int b) { r ...

  10. Git学习笔记--- diff工具 kdiff3

    图形化的git diff 与 git merge工具:kdiff3 1.安装 win10: 去官网左边找到Download,下载双击安装. Linux(Debian Ubuntu 18.04): ap ...