python爬虫系列——requests库

版权声明: https://blog.csdn.net/qq_34246164/article/details/84780603

前言:

           前一篇文章中,我们学习了怎么查看保存在网页中的信息,但要怎么把这些信息从网上抓取下来呢?接下来我们就来解决这个问题。让我们一起走进requests。

一   requests 简介

          Requests是用python语言基于urllib编写的,采用的是Apache2 Licensed开源协议的HTTP库,Requests它会比urllib更加方便,Requests 是以 PEP 20 的箴言为中心开发的

  1. Beautiful is better than ugly.(美丽优于丑陋)
  2. Explicit is better than implicit.(直白优于含蓄)
  3. Simple is better than complex.(简单优于复杂)
  4. Complex is better than complicated.(复杂优于繁琐)
  5. Readability counts.(可读性很重要)

对于 Requests 所有的贡献都应牢记这些重要的准则。

二  安装

requests 的安装有两种方式

第一种:pip 安装

打开cmd,输入下列命令

pip install requests

第二种,whl 文件安装

从这个链接下载对应的requests 的whl 文件,然后在命令行窗口输入下列命令

pip install 'whl文件路径'

推荐使用第一种安装方式。

二   requests 的基本功能介绍

在使用requests时候,第一步要做的就是在文件的头部到导入requests库

import requests

2.1 功能总结

get: 用于获取网页信息,以百度首页为例,获取百度首页的源代码

r = requests.get("http://baidu.com")

这样我们就轻易的获得了网页的源代码。接下来我们可以通过状态码来看下是否成功了

print(r.status_code)

可以看到返回的是

200

那么我们就成功的获取了网页的源代码

那怎么查看获取到的源代码呢?输入下面的命令就可以了

print(r.text)

因此,获取百度搜索首页源代码的程序如下:

import requests

r = requests.get("http://www.baidu.com")

print(r.status_code)                  //打印状态码

if(r.status_code == 200):
    print(len(r.text))                //打印长度
    print(r.text)                     //将网页打印出来

requests 还有其他功能,现阶段相对于get 功能来说,用的不是很多,等到后面需要用到的时候再进行详细介绍,这里制作简单介绍。

import requests
requests.post("http://httpbin.org/post")
requests.put("http://httpbin.org/put")
requests.delete("http://httpbin.org/delete")
requests.head("http://httpbin.org/get")
requests.options("http://httpbin.org/get")

这个系列文章也会在微信公众号,同步更新,欢迎关注。

                                                             

猜你喜欢

转载自blog.csdn.net/qq_34246164/article/details/84780603