春江暮客

春江暮客的个人学习分享网站

python3 requests模块用法实例

2018-12-28 技术
python3 requests模块用法实例
文章目录

Python 3 里做网络请求已经比早期方便很多,而 requests 基本就是最常用、也最适合入门的一套 HTTP 工具。很多日常脚本里,GET、POST、下载文件、带头部访问、带 Cookie 请求这些需求,用它都能很快写出来。

下面就按最常见的场景,用例子整理一下 requests 的基本用法,顺便补几个实战里更推荐的写法。

requests并不是python默认安装的,没安装使用pip install requests安装便是,下面是requests使模块使用实例。 《python3 requests模块用法实例》

GET获取网页内容

import requests
r = requests.get("https://www.bobobk.com/vip_parse")
print("状态码:\n%d" % r.status_code)  #状态码
print(r.headers['content-type']) #头部编码
print("网页内容:\n%s" % r.content.decode("utf8")[:100])#content返回原始数据为byte类型,这里utf8解码输出
print("网页内容:\n%s" % r.text[:100])#text返回str类型

实际项目里通常还会顺手加一句:

r.raise_for_status()

这样当请求返回 404、500 等错误状态时会直接抛异常,比静默继续往下跑更容易排错。

如果带有参数的url呢,也很简单,requests为了方便,不需要你写很长的url到get里面,使用params={url=”https://www.bobobk.com”,id=”1″}这种形式即可
当然你非要写很长的也是可以的,完全没问题。

POST数据

post数据也非常简单,data参数,字典里面写上需要post的数据.

import requests
r = requests.post('https://httpbin.org/post', data = {'key':'value'})

添加数据头

有时网站可能限制了user agent(UA),你直接用默认参数使用的UA是包含了requests的,所以如果修改头的话就是

import requests
headers = {'user-agent': 'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10'}
url="https://httpbin.org/get"
r = requests.get(url, headers=headers,timeout=5)
    #或者使用timeout设置延时

基础验证

有的时候如果网站使用了基础验证的话,只需要添加auth参数即可

r = requests.get(url, headers=headers,timeout=5,auth=HTTPBasicAuth('username', 'password'))
    #由于httpbasicauth比较普遍,python允许不谢验证方法,如下
r = requests.get(url, headers=headers,timeout=5,auth=('username', 'password'))

GET下载文件

 r = requests.get('https://www.bobobk.com/wp-content/uploads/2018/12/wizard.webp')
f = open('download.webp', 'wb')
for chunk in r.iter_content(chunk_size=512 * 1024): 
	if chunk: 
		f.write(chunk)
f.close()

此处使用的方法可以下载大文件

POST文件

当然也是可以直接post文件的,添加参数files,用法

url = 'https://httpbin.org/post'
files = {'file': ('myfile.xls', open('myfile.xls', 'rb'), 'application/vnd.ms-excel', {'Expires': '0'})}
r = requests.post(url, files=files)

使用COOKIE

直接指定cookie参数即可

url = 'https://httpbin.org/cookies'
r = requests.get(url, cookies={"username":"bobobk"})
    #如果是网页返回包含cookie,也可以方便的获取到cookie
r.cookies

多次请求时可以考虑 Session

如果你要连续请求同一个站点,特别是涉及登录状态、公共请求头或者 Cookie 复用时,可以考虑 requests.Session():

session = requests.Session()
session.headers.update({"user-agent": "Mozilla/5.0"})
response = session.get("https://httpbin.org/get")

它的好处是请求之间可以自动复用连接和 Cookie,写批量脚本时会更省事。

参考来源:

1.http://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls

标签

1024 12306 2fa ablang adsense agents.md ai ai-agent ai-agents ai-seo algorithm amp antibodies apparmor argparse automation backup bash batch-processing binarycif bioinformatics biopython blockchain boltz bootstrapping boxes bubblewrap c-index cca cdn chatgpt checkpoint cli cloudflare codex cofoldarena concurrency configparser configuration copy cprofile cpu监控 cron csv cuda curl data-leakage data-processing data-quality data-validation datascience datavisualization datetime debugging decimal deployment desktop-app devtools difflib disk-space disown dns docker dovecot download electron encoding esm esm2 esm3 esmc esmfold2 etag evaluation faceswap fasta fastmcp faulthandler ffmpeg file-descriptors file-io file-management filecmp filenames files flashppi flask folium frontend game generator git github-actions google google-research gpt-6.1-sol grep gzip harness heapq hls html http hugo imports indexnow ipaddress jailbreak javascript jev json jsonl just k-means kaggle langfuse leecode linux list litellm llm llms.txt logging logs lollipop lsof m3u8 machine-learning macos manacher matplotlib mcp memory mirror mmcif model-evaluation monitoring mp3 mp4 mpnn multiomics multiprocessing mutation mysql nanobert nanobodies networking networkx nginx normalize numpy ollama omegatherm pandas password pathlib pdb pep-723 performance permissions phaser pillow pip postfix preprocessing print prompt-engineering protein-alignment protein-design protein-embeddings protein-interactions protein-language-models protein-stability protein-structure proxy pydantic pyecharts pyqt python python3 r raincloud reproducibility requests reservoir-sampling rfoptimization rg ripgrep rosettafold3 roundcube rrsi rsi rsync s-tui sampling scale scikit-learn scrapy screen seaborn security selenium seo sequence-identity sha256 shell signals sitemap sklearn socket solana somaticsignatures sorting spl sql sqlite ssh standardize static-site subprocess symlink sysadmin system-one tarfile tcp tempfile tensorflow tkinter tls toml totp tracemalloc tron tronpy troubleshooting turtle typesafe-ai ubuntu unicode upsert urllib usdt utf-8 uv venv vhhbert vite web-tools webp wordcloud wordpress workflow xml yaml zipfile zoneinfo 后台 寓言 概率 经济 贸易 迅雷解析 钱包

友情链接

其它