Section 91.1: HTTP GET
import requests
print(requests.get("http://stackoverflow.com/"))
# Prints: <Response [200]>
response = requests.get("http://stackoverflow.com/")
print(response.status_code)
# Prints: 200
print(response.read())
# Prints: b'<!DOCTYPE html>\r\n<html>\r\n<head>\r\n\r\n<title>Documentation - Stack Overflow</title>
该模块已针对 Python 3.x 进行了更新,但用例基本保持不变。urllib.request.urlopen 将返回一个类似文件的对象。
Section 91.2: HTTP POST
要传送数据,请将编码后的查询参数作为数据传递给 urlopen()
import urllib.request
import urllib.parse
# 定义请求的URL
url = "https://stackoverflow.com/users/login"
# 定义请求的参数
query_parms = {'username': 'stackoverflow', 'password': 'me.me'}
# 对参数进行编码
encoded_parms = urllib.parse.urlencode(query_parms).encode('utf-8')
# 创建请求对象
req = urllib.request.Request(url, data=encoded_parms, headers={
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
'Content-Type': 'application/x-www-form-urlencoded'
})
try:
# 发送请求
response = urllib.request.urlopen(req)
# 检查响应状态码
print("Response Code:", response.getcode())
# 读取响应内容
content = response.read()
print("Response Content:", content.decode('utf-8'))
except Exception as e:
print("Error:", e)
Section 91.3: 根据内容类型编码对接收到的字节进行解码
接收到的字节必须用正确的字符编码解码,才能被解释为文本:
import urllib.request
# 定义目标 URL
url = "http://stackoverflow.com/"
try:
# 发送 HTTP GET 请求
response = urllib.request.urlopen(url)
# 获取响应内容
data = response.read()
# 获取响应的编码格式
encoding = response.info().get_content_charset()
# 将响应内容解码为字符串
html = data.decode(encoding)
# 打印响应状态码和部分HTML内容
print("Response Code:", response.getcode())
print("HTML Content (first 500 characters):")
print(html[:500]) # 打印前500个字符,避免输出过多内容
except Exception as e:
print("Error:", e)