python---requests库的用法和案例

爬取网页的requests库

1. requests库概述

简洁的处理HTTP请求的第三方库,建立在Python的urllib3库基础上,是对urllib3库的再封装。
requests库包括URL获取、HTTP长连接和连接缓存、自动内容解码、文件分块上传、连接超时处理、流数据下载等功能。

2. requests库解析

requests库的requests.get()方法功能是网络爬虫和信息提交
res=requests.get(url[,timeout=n])
该函数返回的网页内容会保存为一个response对象。参数url必须采用HTTP或HTTPS方式访问,可选参数timeout用于设定每次请求超时时间。

requests.get() 返回的response对象代表响应。response对象的主要属性如下。 ●
statuscode:返回HTTP请求的状态,200表示连接成功,404表示失败。 ●
text:HTTP响应内容的字符串形式,即url对应的页面内容。 ● encoding:HTTP响应内容的编码方式。 ●
content:HTTP响应内容的二进制形式。

Response对象提供了两个方法。 json():如果HTTP响应内容包含JSON格式数据,则该方法解析JSON数据。
raise_for_status():如果status_code值不是200,则产生异常。

3.requests基本操作

(1)增加头部并设置访问代理

>>> url = 'https://api.github.com/some/endpoint'
>>> headers = {'user-agent': 'my-app/0.0.1'}
>>> r = requests.get(url, headers=headers)

(2)访问网页并提交数据

>>> payload = {'key1': 'value1', 'key2': 'value2'}
>>> r = requests.post("http://httpbin.org/post", data=payload)
>>> print(r.text)        #查看网页信息,略去输出结果
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, json=payload)
>>> print(r.text)        #查看网页信息,略去输出结果
>>> print(r.headers)     #查看头部信息,略去输出结果
>>> print(r.headers['Content-Type'])
application/json; charset=utf-8
>>> print(r.headers['Content-Encoding'])
gzip

(3)获取和设置cookies
使用get()方法获取网页信息时cookies属性的用法:

>>> r = requests.get("http://www.baidu.com/")
>>> r.cookies            #查看cookies
<RequestsCookieJar[Cookie(version=0, name='BDORZ', value='27315', port=None, port_specified=False, domain='.baidu.com', domain_specified=True, domain_initial_dot=True, path='/', path_specified=True, secure=False, expires=1521533127, discard=False, comment=None, comment_url=None, rest={}, rfc2109=False)]>

(4)使用get()方法获取网页信息时设置cookies参数的用法:

>>> url = 'http://httpbin.org/cookies'
>>> cookies = dict(cookies_are='working')
>>> r = requests.get(url, cookies=cookies)  #设置cookies
>>> print(r.text)
{
  "cookies": {
    "cookies_are": "working"
  }
}

4.requests爬虫案例

(1)使用requests库爬取微信公众号“Python小屋”文章“Python使用集合实现素数筛选法”中的所有超链接。

>>> import requests
>>> url = 'https://mp.weixin.qq.com/s?__biz=MzI4MzM2MDgyMQ==&mid=2247486531&idx=1&sn=7eeb27a03e2ee8ab4152563bb110f248&chksm=eb8aa719dcfd2e0f7b1731cfd8aa74114d68facf1809d7cdb0601e3d3be8fb287cfc035002c6#rd'
>>> r = requests.get(url)
>>> r.status_code       #响应状态码
200
>>> r.text[:300]        #查看网页源代码前300个字符
'<!DOCTYPE html>\n<!--headTrap<body></body><head></head><html></html>--><html>\n    <head>\n        <meta http-equiv="Content-Type" content="text/html; charset=utf-8">\n<meta http-equiv="X-UA-Compatible" content="IE=edge">\n<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale='
>>> '筛选法' in r.text  #测试网页源代码中是否包含字符串'筛选法'
True
>>> r.encoding          #查看网页编码格式
'UTF-8'
>>> links = re.findall(r'<a .*?href="(.+?)"', r.text)
                          #使用正则表达式查找所有超链接地址
>>> for link in links:
    if link.startswith('http'):
        print(link)
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(r.content, 'lxml')
>>> for link in soup.findAll('a'):  #使用BeautifulSoup查找超链接地址
    href = link.get('href')
    if href.startswith('http'):      #只输出绝对地址
        print(href)

(2)读取并下载指定的URL的图片文件。

>>> import requests
>>> picUrl = r'https://www.python.org/static/opengraph-icon-200x200.png'
>>> r = requests.get(picUrl)
>>> r.status_code
200
>>> with open('pic.png', 'wb') as fp:
    fp.write(r.content)                #把图像数据写入本地文件
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值