python requests【1】处理url模块

简介: python requests【1】处理url模块

python 模块 requests (1) 处理url

文章目录

1. 简介

requests 是python的一个HTTP客户端库,跟urllib,urllib2类似,那为什么要用requests而不用urllib2呢?

2. 安装

pip install requests

3. 方法

import requests

HTTP请求:GET、POST、PUT、DELETE、HEAD、OPTIONS

requests.get("http://xxxx.com/")
requests.post("http://xxxx.com/post", data = {'key':'value'})
requests.put("http://xxxx.com/put", data = {'key':'value'})
requests.delete("http://xxxx.com/delete")
requests.head("http://xxxx.com/get")
requests.options("http://xxxx.com/get")
 为URL传递参数
  requests模块使用params关键字参数,以一个字典的形式来提供参数。
>>> payload = {'key1':'value','key2':'value2'}
>>> res = requests.get("http://httpbin.org/get",params=payload)
>>> res.url
u'http://httpbin.org/get?key2=value2&key1=value'
>>> r = requests.get('http://www.zhidaow.com')  # 发送请求
>>> r.status_code  # 返回码 
200
>>> r.headers['content-type']  # 返回头部信息
'text/html; charset=utf8'
>>> r.encoding  # 编码信息
'utf-8'
>>> r.text  #内容部分(PS,由于编码问题,建议这里使用r.content)
u'<!DOCTYPE html>\n<html xmlns="http://www.w3.org/1999/xhtml"...'
...
>>> res.json()
>>> res.raw

response.text和response.content的区别在于:


response.text是解过码的字符串(比如html代码)。当requests发送请求到一个网页时,requests库会推测目标网页的编码,并对其解码,转为字符串(str)。这种方法比较容易出现乱码。

response.content是未解码的二进制格式(bytes),不仅支持文本内容,还适用于二进制文件内容如图片和音乐等。如果需要把文本内容转化为字符串,一般使用response.content.decode(‘utf-8’)方法即可。

3.1 发送带参数的get请求

import requests
params = {
    "wd": "python", "pn": 10,
}
response = requests.get('https://www.baidu.com/s', params=params)
print(response.url)
print(response.text)

3.2 发送带数据的post请求

import requests
post_data = {'username': 'value1', 'password': 'value2'}
response = requests.post("http://xxx.com/login/", data=post_data)
response.raise_for_status()

3.3 post也可以用于上传文件

>>> import requests
>>> url = 'http://httpbin.org/post'
>>> files = {'file': open('report.xls', 'rb')}
>>> r = requests.post(url, files=files)

3.4 设置与查看请求头(headers)

很多网站都有反爬机制,如果一个请求不携带请求头headers, 很可能被禁止访问。我们可以按如下方式设置请求头。你也可以通过打印response.headers查看当前请求头。

import requests
headers = {
    "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_4) AppleWebKit/"
                 "537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36"
}
response1 =requests.get("https://www.baidu.com", headers=headers)
response2 =requests.post("https://www.xxxx.com", data={"key": "value"}, 
headers=headers)
print(response1.headers)
print(response1.headers['Content-Type'])
print(response2.text)

3.5 代理Proxy

有的网站反爬机制会限制单位时间内同一IP的请求次数,这时我们可以通过设置IP proxy代理来应对这个反爬机制。requests里设置proxy也非常简单,如下面代码所示。

import requests
proxies = {
  "http": "http://10.10.1.10:3128",
  "https": "http://10.10.1.10:1080",
}
requests.get("http://example.org", proxies=proxies)

3.6 保存cookies

cookies = requests.cookies.RequestsCookieJar()
def login(endpointip):
    endpoint = "http://" + endpointip + ":8080/upcdb_manager/v1.0/login"
    header = {}
    header['Content-Type'] = "application/json"
    payload = {
        "loginName": username,
        "password": password
    }
    response = requests.request("POST", endpoint, data=json.dumps(payload),headers=header)
    return response.cookies
if __name__ == '__main__':
    cookies = login('192.168.1.19')
    url = 'www.baidu.com/xxx'
   r = requests.get(url,cookies=cookies)

✈推荐阅读:

相关文章
|
3月前
|
存储 Web App开发 前端开发
Python + Requests库爬取动态Ajax分页数据
Python + Requests库爬取动态Ajax分页数据
|
3月前
|
Web App开发 安全 数据安全/隐私保护
利用Python+Requests实现抖音无水印视频下载
利用Python+Requests实现抖音无水印视频下载
|
22天前
|
安全 大数据 程序员
Python operator模块的methodcaller:一行代码搞定对象方法调用的黑科技
`operator.methodcaller`是Python中处理对象方法调用的高效工具,替代冗长Lambda,提升代码可读性与性能。适用于数据过滤、排序、转换等场景,支持参数传递与链式调用,是函数式编程的隐藏利器。
71 4
|
16天前
|
存储 数据库 开发者
Python SQLite模块:轻量级数据库的实战指南
本文深入讲解Python内置sqlite3模块的实战应用,涵盖数据库连接、CRUD操作、事务管理、性能优化及高级特性,结合完整案例,助你快速掌握SQLite在小型项目中的高效使用,是Python开发者必备的轻量级数据库指南。
141 0
|
3月前
|
JSON 网络安全 数据格式
Python网络请求库requests使用详述
总结来说,`requests`库非常适用于需要快速、简易、可靠进行HTTP请求的应用场景,它的简洁性让开发者避免繁琐的网络代码而专注于交互逻辑本身。通过上述方式,你可以利用 `requests`处理大部分常见的HTTP请求需求。
324 51
|
2月前
|
存储 安全 数据处理
Python 内置模块 collections 详解
`collections` 是 Python 内置模块,提供多种高效数据类型,如 `namedtuple`、`deque`、`Counter` 等,帮助开发者优化数据处理流程,提升代码可读性与性能,适用于复杂数据结构管理与高效操作场景。
111 0
|
3月前
|
数据安全/隐私保护 Python
抖音私信脚本app,协议私信群发工具,抖音python私信模块
这个实现包含三个主要模块:抖音私信核心功能类、辅助工具类和主程序入口。核心功能包括登录
|
3月前
|
数据采集 API 调度
Python爬虫框架对比:Scrapy vs Requests在API调用中的应用
本文对比了 Python 中 Scrapy 与 Requests 两大爬虫框架在 API 调用中的差异,涵盖架构设计、调用模式、性能优化及适用场景,并提供实战建议,助力开发者根据项目需求选择合适工具。
|
4月前
|
JSON 数据格式 Python
解决Python requests库POST请求参数顺序问题的方法。
总之,想要在Python的requests库里保持POST参数顺序,你要像捋顺头发一样捋顺它们,在向服务器炫耀你那有条不紊的数据前。抓紧手中的 `OrderedDict`与 `json`这两把钥匙,就能向服务端展示你的请求参数就像经过高端配置的快递包裹,里面的商品摆放井井有条,任何时候开箱都是一种享受。
106 10

推荐镜像

更多