Python爬虫
来源:互联网 发布:淘宝店铺店标在线制作 编辑:程序博客网 时间:2024/04/28 00:21
安装Requests库
启动cmd控制台, 安装Requests库(pip install requests)
测试安装效果:启动IDLE
>>> import requests >>> r = requests.get("http://www.baidu.com") >>> r.status_code 200 >>> r.encoding = 'utf-8' >>> r.text
成功抓取百度主页
Requests库的get()方法
r = requests.get(url)
Requests库的2个重要对象:Response(包含爬虫返回的内容)和Request
Response对象的属性
r.status_code HTTP请求的返回状态,200表示连接成功,404表示失败
r.text HTTP响应内容的字符串形式,即url对应的页面内容
r.encoding 从HTTP header中猜测的响应内容编码方式(
r.apparent_encoding 从内容中分析出的响应内容编码方式(备选编码方式)
r.content HTTP响应内容的二进制形式
get方法获取网上资源的基本流程:用r.status_code检查返回状态 ,
情况1:如果是200,可以用r.text、r.encoding、r.apparent_encoding、r.content解析返回的内容;
情况2:返回的是404或者其他,则访问不成功
r.encoding和r.apparent_encoding的区别
r.encoding:如果header中不存在charset,则认为编码为ISO-8859-1
r.apparent_encoding:根据网页内容分析出的编码方式
综上所述,r.apparent_encoding比r.encoding更为准确
**r.raise_for_status()**Requests库用于检验异常
爬取网页的通用代码框架
def getHTMLText(url): try: r=requests.get(url,timeout30) r.raise_for_status #如果状态不是200,引发HTTPError异常 r.encoding = r.apparent_encoding return r.text ecxept: return #产生异常
保证网络连接的异常能够被有效处理
网络爬虫的限制
来源审查:判断User-Agent进行限制
检查来访HTTP协议头的User-agent域,只响应浏览器或者友好爬虫访问
发布公告:Robots协议
告知所有爬虫网站的爬取策略,要求爬虫遵守
Robots协议基本语法
User-agent:*
Disallow: /
* 代表所有 , / 代表根目录
实例
(1)京东商品页面的爬取
>>> import requests >>> r = requests.get("http://sale.jd.com/act/L1Y2V6ERZePab4.html?cpdad=1DLSUE") >>> r.status_code 200 >>> r.encoding 'utf-8' >>> r.text[:1000]
(2)亚马逊商品页面的爬取
(3)360搜索关键词提交
>>> import requests >>> kv = { 'wd':'Python'} >>> r = requests.get("http://www.baidu.com/s",params = kv) >>> r.status_code 200 >>> r.request.url'http://www.baidu.com/s?wd=Python' >>> len(r.text) 264348
(4)网络图片的爬取与存储
(二进制格式的图片、动画、视频等都可以爬取)
>>> import requests >>> path = "E://abc.jpg" >>> url = "http://p7.qhmsg.com/t0142c4b9ee48e461ed.jpg" >>> r = requests.get(url) >>> r.status_code 200 >>> with open(path,'wb') as f: f.write(r.content) >>> f.close <built-in method close of file object at 0x00000000042979C0>
图片则保存在E盘中
(5)IP地址归属地的自动查询
>>> import requests >>> url = 'http://m.ip138.com/ip.asp?ip=' >>> r.status_code 200 >>> r.text[-500:]
- python爬虫-->爬虫基础
- [爬虫] Python爬虫技巧
- Python爬虫
- python 爬虫
- python 爬虫
- python 爬虫
- python爬虫
- Python爬虫
- Python爬虫
- python 爬虫
- Python爬虫
- python爬虫
- python 爬虫
- python 爬虫
- python爬虫
- python爬虫
- python爬虫
- python 爬虫
- 清除浮动造成的塌陷
- python 知识点(五)面向对象
- 谷歌Gson入门篇
- HashMap实现原理分析
- Go语言开发Android程序
- Python爬虫
- 在O(1)时间复杂度删除链表节点
- 系统时间
- Struts2 XML配置详解
- VC6.0绿色版安装
- web.config配置连接字符串的方法
- TensorFlow Mac CPU only 安装详细步骤,跟着步骤来一次性到位准保成功
- 成为第三大操作系统,YunOS用了这四大招
- Git基础(一)--安装和配置SSH-Key