day31-20180612笔记

笔记:Python3 爬虫css

 

1、爬虫
html

requests库是一个经常使用的用于http请求的模块,它使用python语言编写,能够方便的对网页进行爬取,是学习python爬虫的较好的http请求模块。

1、 requests模块的安装

首先咱们要继续requests模块的安装。python

一、 pip命令安装

  • 在windows系统下只须要在命令行输入命令 pip install requests 便可安装。linux

  • 在 linux 系统下,只须要输入命令 sudo pip install requests ,便可安装。git

二、下载安装包安装

因为pip命令可能安装失败因此有时咱们要经过下载第三方库文件来进行安装。github

在github上的地址为:https://github.com/requests/requests 
下载文件到本地以后,解压到python安装目录。 
以后打开解压文件,在此处运行命令行并输入:python setup.py install 便可。web

以后咱们测试requests模块是否安装正确,在交互式环境中输入 import requests 若是没有任何报错,说明requests模块咱们已经安装成功了json

2、requests模块的使用方法

一、requests库的七个主要方法

 

方法 解释
requests.request() 构造一个请求,支持如下各类方法
requests.get() 获取html的主要方法
requests.head() 获取html头部信息的主要方法
requests.post() 向html网页提交post请求的方法
requests.put() 向html网页提交put请求的方法
requests.patch() 向html提交局部修改的请求
requests.delete() 向html提交删除请求


(1)requests.get()

这个方法是咱们平时最经常使用的方法之一,经过这个方法咱们能够了解到其余的方法,因此咱们详细介绍这个方法。 
具体参数是:windows

r=requests.get(url,params,**kwargs)
    • url: 须要爬取的网站地址。
    • params: 翻译过来就是参数, url中的额外参数,字典或者字节流格式,可选。
    • **kwargs : 12个控制访问的参数 
      咱们先来说讲**kwargs:

**kwargs有如下的参数,对于requests.get,其第一个参数被提出来了。浏览器

  • params:字典或字节序列, 做为参数增长到url中,使用这个参数能够把一些键值对以?key1=value1&key2=value2的模式增长到url中 
    例如:kv = {‘key1: ’ values’, ‘key2’: ‘values’} 
    r = requests.request(‘GET’, ‘http:www.python123.io/ws’, params=kw)
  • data:字典,字节序或文件对象,重点做为向服务器提供或提交资源是提交,,做为request的内容,与params不一样的是,data提交的数据并不放在url连接里, 而是放在url连接对应位置的地方做为数据来存储。,它也能够接受一个字符串对象。
  • json:json格式的数据, json合适在相关的html,http相关的web开发中很是常见, 也是http最常用的数据格式, 他是做为内容部分能够向服务器提交。 
    例如:kv = {”key1’: ‘value1’} 
    r = requests.request(‘POST’, ‘http://python123.io/ws‘, json=kv)

  • headers:字典是http的相关语,对应了向某个url访问时所发起的http的头i字段, 能够用这个字段来定义http的访问的http头,能够用来模拟任何咱们想模拟的浏览器来对url发起访问。 
    例子: hd = {‘user-agent’: ‘Chrome/10’} 
    r = requests.request(‘POST’, ‘http://python123.io/ws‘, headers=hd)

  • cookies:字典或CookieJar,指的是从http中解析cookie

  • auth:元组,用来支持http认证功能

  • files:字典, 是用来向服务器传输文件时使用的字段。 
    例子:fs = {‘files’: open(‘data.txt’, ‘rb’)} 
    r = requests.request(‘POST’, ‘http://python123.io/ws‘, files=fs)

  • timeout: 用于设定超时时间, 单位为秒,当发起一个get请求时能够设置一个timeout时间, 若是在timeout时间内请求内容没有返回, 将产生一个timeout的异常。

  • proxies:字典, 用来设置访问代理服务器。

  • allow_redirects: 开关, 表示是否容许对url进行重定向, 默认为True。

  • stream: 开关, 指是否对获取内容进行当即下载, 默认为True。

  • verify:开关, 用于认证SSL证书, 默认为True。

  • cert: 用于设置保存本地SSL证书路径

    这句代码是构造一个服务器请求request,返回一个包含服务器资源的response对象。

其中response对象有如下属性:

 

属性 说明
r.status_code http请求的返回状态,若为200则表示请求成功。
r.text http响应内容的字符串形式,即返回的页面内容
r.encoding 从http header 中猜想的相应内容编码方式
r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
r.content http响应内容的二进制形式
举例说明:
>>> import requests
>>> r=requests.get("http://www.baidu.com")
>>> r.status_code
200
>>>  r.encoding
'ISO-8859-1'
>>> r.apparent_encoding
'utf-8'
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8>ipt> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b´å¤\x9a产å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé¦\x88</a>&nbsp;京ICPè¯\x81030173å\x8f·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'
>>> r.encoding='utf-8'
>>> r.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta chref=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css="h读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>意见反馈</a>&nbsp;京ICP证030173号&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'

(以上r.text内容过长,自行删除了部分,看出编码效果便可)

requests库的异常 
注意requests库有时会产生异常,好比网络链接错误、http错误异常、重定向异常、请求url超时异常等等。因此咱们须要判断r.status_codes是不是200,在这里咱们怎么样去捕捉异常呢?

这里咱们能够利用r.raise_for_status() 语句去捕捉异常,该语句在方法内部判断r.status_code是否等于200,若是不等于,则抛出异常。

因而在这里咱们有一个爬取网页的通用代码框架:

try:
    r=requests.get(url,timeout=30)#请求超时时间为30秒
    r.raise_for_status()#若是状态不是200,则引起异常
    r.encoding=r.apparent_encoding #配置编码
    return r.text
except:
    return"产生异常"

(2) request.head()

看代码:

 >>> r=requests.head("http://httpbin.org/get")
 >>>r.headers
 {'Connection': 'keep-alive', 'Server': 'meinheld/0.6.1', 'Date': 'Mon, 20 Nov 2017 08:08:46 GMT', 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Credentials': 'true', 'X-Powered-By': 'Flask', 'X-Processed-Time': '0.000658988952637', 'Content-Length': '268', 'Via': '1.1 vegur'}
 >>>r.text
 ""

(4)requests.post()

一、向url post一个字典:

>>> payload={"key1":"value1","key2":"value2"}
>>> r=requests.post("http://httpbin.org/post",data=payload)
>>> print(r.text)
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "key1": "value1", 
    "key2": "value2"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "23", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "origin": "218.197.153.150", 
  "url": "http://httpbin.org/post"
}

 

二、向url post 一个字符串,自动编码为data

>>>r=requests.post("http://httpbin.org/post",data='helloworld')
>>>print(r.text)
{
  "args": {}, 
  "data": "helloworld", 
  "files": {}, 
  "form": {}, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "10", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "origin": "218.197.153.150", 
  "url": "http://httpbin.org/post"
}

(5)requests.put()

看代码:

>>> payload={"key1":"value1","key2":"value2"}
>>> r=requests.put("http://httpbin.org/put",data=payload)
>>> print(r.text)
{
  "args": {}, 
  "data": "", 
  "files": {}, 
  "form": {
    "key1": "value1", 
    "key2": "value2"
  }, 
  "headers": {
    "Accept": "*/*", 
    "Accept-Encoding": "gzip, deflate", 
    "Connection": "close", 
    "Content-Length": "23", 
    "Content-Type": "application/x-www-form-urlencoded", 
    "Host": "httpbin.org", 
    "User-Agent": "python-requests/2.18.4"
  }, 
  "json": null, 
  "origin": "218.197.153.150", 
  "url": "http://httpbin.org/put"

(6)requests.patch()

requests.patch和request.put相似。 
二者不一样的是: 
当咱们用patch时仅须要提交须要修改的字段。 
而用put时,必须将20个字段一块儿提交到url,未提交字段将会被删除。 
patch的好处是:节省网络带宽。

(7)requests.request()

requests.request()支持其余全部的方法。 
requests.request(method,url,**kwargs)

    • method: “GET”、”HEAD”、”POST”、”PUT”、”PATCH”等等
    • url: 请求的网址
    • **kwargs: 控制访问的参数

3、requests模块的使用实例

一、京东商品信息的爬取

不须要对头部作任何修改,便可爬网页

import requests
url='http://item.jd.com/2967929.html'
try:
    r=requests.get(url,timeout=30)
    r.raise_for_status()
    r.encoding=r.apparent_encoding 
    print(r.text[:1000]) #部分信息
except:
    print("失败"

二、亚马逊商品信息的爬取

该网页中对爬虫进行的爬取作了限制,所以咱们须要假装本身为浏览器发出的请求。

import requests
url='http://www.amazon.cn/gp/product/B01M8L5Z3Y'
try:
    kv={'user_agent':'Mozilla/5.0'}
    r=requests.get(url,headers=kv)#改变本身的请求数据
    r.raise_for_status()
    r.encoding=r.apparent_encoding 
    print(r.text[1000:2000]) #部分信息
except:
    print("失败"

三、百度搜索关键字提交

百度的关键字接口: 
https://www.baidu.com/s?wd=keyword

import requests
keyword='python'
try:
    kv={'wd':keyword}
    r=requests.get('https://www.baidu.com/s',params=kv)
    r.raise_for_status()
    r.encoding=r.apparent_encoding 
    print(len(r.text)) 
except:
    print("失败"

四、网络图片的爬取

import requests
import os
try:
    url="http://baishi.baidu.com/watch/02167966440907275567.html"#图片地址
    root="E:/pic/"
    path=root+url.split("/")[-1]
    if not os.path.exists(root): #目录不存在建立目录
        os.mkdir(root)
    if not os.path.exists(path): #文件不存在则下载
        r=requests.get(url)
        f=open(path,"wb")
        f.write(r.content)
        f.close()
        print("文件下载成功")
    else:
        print("文件已经存在")
except:
    print("获取失败")

 

 

上课代码;

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/6/12 21:03
# @Author  : yangyuanqiang
# @File    : demon1.py


import requests

# get请求
# wd = "python"
# url = "http://www.baidu.com/s?wd={0}".format(wd)
# r = requests.get(url)
# r.encoding = "utf-8"
# html = r.text
# print(html)


wd = "python"
params = {"wd": "hello"}
url = "http://www.baidu.com/s"
r = requests.get(url=url, params=params)
r.encoding = "utf-8"
print(r.url)
html = r.text
# print(html)
 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/6/12 21:50
# @Author  : yangyuanqiang
# @File    : demon2.py

import requests

# post请求
url = "https://www.qiushibaike.com"
header = {"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36"}
r = requests.get(url=url, headers=header)
print(r.request)
print(r.headers)
print(r.encoding)
print(r.cookies)
print(r.cookies.get("_xsrf"))
print(r.url)
print(r.status_code)
相关文章
相关标签/搜索