爬虫初窥day4:requests

news/2024/7/19 9:56:15 标签: 爬虫, json, 移动开发
 

Requests 是使用 Apache2 Licensed 许可证的 HTTP 库。用 Python 编写,真正的为人类着想。

Python 标准库中的 urllib2 模块提供了你所需要的大多数 HTTP 功能,但是它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。

在Python的世界里,事情不应该这么麻烦。

Requests 使用的是 urllib3,因此继承了它的所有特性。Requests 支持 HTTP 连接保持和连接池,支持使用 cookie 保持会话,支持文件上传,支持自动确定响应内容的编码,支持国际化的 URL 和 POST 数据自动编码。现代、国际化、人性化。

(以上转自Requests官方文档)

2、Requests模块安装

点此下载

然后执行安装

1
$ python setup.py install

个人推荐使用pip安装

1
pip install requests

也可以使用easy_install安装

1
easy_install requests

尝试在IDE中import requests,如果没有报错,那么安装成功。

3、Requests模块简单入门

复制代码
#HTTP请求类型
#get类型
r = requests.get('https://github.com/timeline.json') #post类型 r = requests.post("http://m.ctrip.com/post") #put类型 r = requests.put("http://m.ctrip.com/put") #delete类型 r = requests.delete("http://m.ctrip.com/delete") #head类型 r = requests.head("http://m.ctrip.com/head") #options类型 r = requests.options("http://m.ctrip.com/get") #获取响应内容 print r.content #以字节的方式去显示,中文显示为字符 print r.text #以文本的方式去显示 #URL传递参数 payload = {'keyword': '日本', 'salecityid': '2'} r = requests.get("http://m.ctrip.com/webapp/tourvisa/visa_list", params=payload) print r.url #示例为http://m.ctrip.com/webapp/tourvisa/visa_list?salecityid=2&keyword=日本 #获取/修改网页编码 r = requests.get('https://github.com/timeline.json') print r.encoding r.encoding = 'utf-8' #json处理 r = requests.get('https://github.com/timeline.json') print r.json() #需要先import json #定制请求头 url = 'http://m.ctrip.com' headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'} r = requests.post(url, headers=headers) print r.request.headers #复杂post请求 url = 'http://m.ctrip.com' payload = {'some': 'data'} r = requests.post(url, data=json.dumps(payload)) #如果传递的payload是string而不是dict,需要先调用dumps方法格式化一下 #post多部分编码文件 url = 'http://m.ctrip.com' files = {'file': open('report.xls', 'rb')} r = requests.post(url, files=files) #响应状态码 r = requests.get('http://m.ctrip.com') print r.status_code #响应头 r = requests.get('http://m.ctrip.com') print r.headers print r.headers['Content-Type'] print r.headers.get('content-type') #访问响应头部分内容的两种方式 #Cookies url = 'http://example.com/some/cookie/setting/url' r = requests.get(url) r.cookies['example_cookie_name'] #读取cookies  url = 'http://m.ctrip.com/cookies' cookies = dict(cookies_are='working') r = requests.get(url, cookies=cookies) #发送cookies #设置超时时间 r = requests.get('http://m.ctrip.com', timeout=0.001) #设置访问代理 proxies = { "http": "http://10.10.10.10:8888", "https": "http://10.10.10.100:4444", } r = requests.get('http://m.ctrip.com', proxies=proxies)
复制代码

4、Requests示例

json请求

复制代码
 1 #!/user/bin/env python
 2 #coding=utf-8  3 import requests  4 import json  5  6 class url_request():  7 def __init__(self):  8 """ init """  9 10 if __name__=='__main__': 11 headers = {'Content-Type' : 'application/json'} 12 payload = {'CountryName':'中国', 13 'ProvinceName':'陕西省', 14 'L1CityName':'汉中', 15 'L2CityName':'城固', 16 'TownName':'', 17 'Longitude':'107.33393', 18 'Latitude':'33.157131', 19 'Language':'CN' 20  } 21 r = requests.post("http://www.xxxxxx.com/CityLocation/json/LBSLocateCity",headers=headers,data=payload) 22 #r.encoding = 'utf-8' 23 data=r.json() 24 if r.status_code!=200: 25 print "LBSLocateCity API Error " + str(r.status_code) 26 print data['CityEntities'][0]['CityID'] #打印返回json中的某个key的value 27 print data['ResponseStatus']['Ack'] 28 print json.dumps(data,indent=4,sort_keys=True,ensure_ascii=False) #树形打印json,ensure_ascii必须设为False否则中文会显示为unicode
复制代码

 

xml请求

复制代码
#!/user/bin/env python
#coding=utf-8
import requests class url_request(): def __init__(self): """ init """ if __name__=='__main__': headers = {'Content-type': 'text/xml'} XML = '<?xml version="1.0" encoding="utf-8"?><soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><Request xmlns="http://tempuri.org/"><jme><JobClassFullName>WeChatJSTicket.JobWS.Job.JobRefreshTicket,WeChatJSTicket.JobWS</JobClassFullName><Action>RUN</Action><Param>1</Param><HostIP>127.0.0.1</HostIP><JobInfo>1</JobInfo><NeedParallel>false</NeedParallel></jme></Request></soap:Body></soap:Envelope>' url = 'http://jobws.push.mobile.xxxxxxxx.com/RefreshWeiXInTokenJob/RefreshService.asmx' r = requests.post(url,headers=headers,data=XML) #r.encoding = 'utf-8' data = r.text print data
复制代码

 

5、参考文档

http://cn.python-requests.org/en/latest/

http://docs.python-requests.org/en/latest/user/quickstart.html

转载于:https://www.cnblogs.com/p0pl4r/p/10582891.html


http://www.niftyadmin.cn/n/929126.html

相关文章

实战|记一次攻防演练打点

攻防演练已经过去了&#xff0c;简单的写个记录&#xff0c;表示我曾来过 ----------ECHO: 2022/6/2 0x01.外网打点 基础内容参考这位师傅https://mp.weixin.qq.com/s/v2daZNPj5US_4-5tbhBLCA hvv外网打点第一天很重要&#xff0c;要快速从给的资产中找到好打的单位&#xf…

php中的线程、进程和并发区别

https://mp.weixin.qq.com/s/Ps5w13TTmpnZx-RPWbsl1A 进程 进程是什么&#xff1f;进程是正在执行的程序&#xff1b;进程是正在计算机上执行的程序实例&#xff1b;进程是能分配给处理器并由处理器执行的实体。进程一般会包括指令集和系统资源集&#xff0c;这里的指令集是指程…

Tomcat服务器调优

一,目标:优化tomcat来提高访问的并发能力. 服务器提供的内存,cpu,以及硬盘的性能对数据的处理起决定性作用。tomcat的3种运行模式 tomcat的运行模式有3种&#xff1a; 1、 bio默认的模式,性能非常低下,没有经过任何优化处理和支持. 2、 nionio(new I/O)&#xff0c;是Java SE 1…

应急响应全栈

前言: 7月4号就入厂了&#xff0c;兄弟们&#xff0c;还剩一波机会&#xff0c;认真学了相关应急的内容后做了份全栈脑图&#xff0c;解决面试的时候面对空气不知道说什么的咎境。 做的可能不是很对&#xff0c;辅助作用而已&#xff0c;我的理解 实际HW应急: 1.冰蝎的的内存…

在学习Python的过程中需要注意的点

一、学习流程1.学习过程中&#xff08;看视频、直播课程、书籍&#xff09;跟上思路一旦发现不懂的概念, 先记录在笔记中, 事后再查搜索引擎&#xff08;不要在意百度&#xff0c;谷歌哪个逼格高&#xff1b;自己注意筛选就好&#xff09;查不到&#xff0c;或者查到不理解&…

HanLP自然语言处理包开源

中文分词≠自然语言处理&#xff01; 中文分词只是第一步&#xff1b;HanLP从中文分词开始&#xff0c;覆盖词性标注、命名实体识别、句法分析、文本分类等常用任务&#xff0c;提供了丰富的API。 不同于一些简陋的分词类库&#xff0c;HanLP精心优化了内部数据结构和IO接口&am…

实战 || 某web厂商通用漏洞挖掘后续

背景: 这段时间在hw&#xff0c;事情太多&#xff0c;前两天做测试&#xff0c;玩的有点过火&#xff0c;3点多验证到某单位某洞&#xff0c;第二天听说抓人&#xff0c; 吓得我一身冷汗&#xff0c;直接吧vps关了&#xff0c;md&#xff0c;差点吧人挖没了。 腾出来一些时间&…

收藏 40 2 CPD (广告合作方式)

CPD&#xff0c;Cost per day的缩写&#xff0c;意思是按天收费&#xff0c;是一种广告合作方式。在实际的广告合作中根据行业不同还包括Cost per Download的缩写含义&#xff0c;意思是依据实际下载量收费。“CPD"&#xff08;按天收费 Cost per day&#xff09;是广告合…