Python 网络爬虫与信息获取(一)—— requests 库的网络爬虫
2017-04-01 22:43
756 查看
1. 安装与测试
进入cmd(以管理员权限),使用 pip 工具,
pip install requests进行安装;
基本用法:
>> import requests >> r = requests.get('http://www.baidu.com') # 访问百度主页 >> r.status_code 200 # 状态码,200 表示访问成功 >> r.encoding = 'utf-8' # 修改编码 >> r.text # 打印网页内容
2. requests 库的七个主要方法
request:构造一个请求,是构造以下各方法的基础方法;后续的 6 个方法均需调用 request 方法;
get:获取 html 网页的主要方法,对应于 http 的 get;
r = requests.get(url)
构造一个向服务器请求资源的 Request 对象;
返回一个包含服务器资源的 Response 对象;
head:获取 html 网页头信息,对应于 http 的 head;
post:向 html 网页提交 post 请求,对应于 http 的 post;
put:向 html 网页提交 put 请求,对应于 http 的 put;
patch:向 html 网页提交局部修改请求(patch,补丁,也就是修改,局部更新),对应于 http 的 patch;
delete:向 html 页面提交删除请求,对应于 http 的 delete;
4. Response 对象的属性
r.status_coder.status_code == requests.codes.ok,如果返回 True,则表示打开正常;
r.text:http 相应内容的字符串形式,
r.content:http 相应内容的二进制形式;
r.encoding:猜测的编码,从 headers 中的 charset 中获得,但并非所有的服务器都会对其相关资源的编码进行规定和要求;
如果 headers 中不存在 charset,则认为(猜测)其编码为
ISO-8859-1
r.apparent_encoding:根据内容分析出的编码方式,备选编码;
>> r = requests.get('http://www.baidu.com') >> r.encoding 'ISO-8859-1' >> r.apparent_encoding 'utf-8' >> r.encoding = r.apparent_encoding
5. 与其他库的结合
BeautifulSoup:做 html 页面的解析;>> from bs4 import BeautifulSoup >> r = requests.get(url) >> BeautifulSoup(r.text).get_text()
相关文章推荐
- Python网络爬虫与信息提取(三):网络爬虫之实战
- Python网络爬虫与信息提取(二):网络爬虫之提取
- Python网络爬虫与信息提取(二):网络爬虫之提取
- Python网络爬虫与信息提取(一):网络爬虫之规则
- (一)表层网络信息获取(Python引擎爬虫)
- Python实现可获取网易页面所有文本信息的网易网络爬虫功能示例
- Python网络爬虫与信息提取(三):网络爬虫之实战
- python获取网络文件信息
- 【网络爬虫】【python】网络爬虫(三):模拟登录——伪装浏览器登录爬取过程
- 【极客学院】-python学习笔记-3-单线程爬虫 (request安装遇到问题及解决,应用requests提取信息)
- Python网络爬虫(一):初步认识网络爬虫
- python爬虫 - python requests网络请求简洁之道
- Python网络编程小例子:使用python获取网站域名信息
- [Python爬虫] Selenium+Phantomjs动态获取CSDN下载资源信息和评论
- Python爬虫框架Scrapy实战之定向批量获取职位招聘信息
- Python Requests爬虫——获取一个收藏夹下所有答案的图片
- python爬虫 - python requests网络请求简洁之道
- 【网络爬虫】【python】网络爬虫(一):python爬虫概述
- python 爬虫获取网站信息(一)
- python获取网络文件信息藏