Python网络编程

Python HTTP客户端

Python HTTP客户端详细操作教程
在http协议中,来自客户端的请求到达服务器,并假定它是有效请求,并获取一些数据和元数据。可以使用python请求模块中提供的各种功能来分析服务器的响应。下面的python程序在客户端运行,并显示服务器发送的响应结果。

取得初步响应

在下面的程序中,requests模块的get方法从服务器获取数据,并以纯文本格式打印。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-25
import requests
r = requests.get('https://httpbin.org/')
print(r.text)[:200]
当运行上面的程序时,得到以下输出-
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-25
<!DOCTYPE html >
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>httpbin.org</title>
  <link
href="https://fonts.googleapis.com/css?family=Open+Sans:400,700|Source+Code+Pro:300,600|Titillium+

获取会话对象响应

通过Session对象,可以在请求中保留某些参数。它还会在会话实例发出的所有请求中保留cookie。如果要向同一主机发出多个请求,则基础TCP连接将被重用。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-25
import requests
s = requests.Session()
s.get('http://httpbin.org/cookies/set/sessioncookie/yyyxxxx1425')
r = s.get('http://httpbin.org/cookies')
print(r.text)
运行上面示例代码,得到以下结果:
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-25
{"cookies":{"sessioncookie":"yyyxxxx1425"}}

处理错误

如果由于服务器处理请求时出现问题而引起一些错误,则python程序可以使用timeout参数正常处理引发的异常,如下所示。程序将等待超时错误的定义值,然后引发超时错误。
# Filename : example.py
# Copyright : 2020 By Lidihuo
# Author by : www.lidihuo.com
# Date : 2020-08-25
requests.get('http://github.com', timeout=10.001)
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4