Python 模拟 HTTP 请求:方法详解及代码示例
Python可以使用多种方式模拟HTTP请求,以下是其中的几种:
- 使用urllib库
import urllib.request
url = 'http://www.example.com'
response = urllib.request.urlopen(url)
print(response.read().decode('utf-8'))
- 使用requests库
import requests
url = 'http://www.example.com'
response = requests.get(url)
print(response.text)
- 使用http.client库
import http.client
conn = http.client.HTTPSConnection('www.example.com')
conn.request('GET', '/')
response = conn.getresponse()
print(response.read().decode('utf-8'))
- 使用socket库
import socket
host = 'www.example.com'
port = 80
request = b'GET / HTTP/1.1\r\nHost: ' + host.encode() + b'\r\n\r\n'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
s.send(request)
response = s.recv(4096)
print(response.decode('utf-8'))
s.close()
以上是几种常见的模拟HTTP请求的方法,可以根据实际需求选择合适的方法。
原文地址: https://www.cveoy.top/t/topic/jskB 著作权归作者所有。请勿转载和采集!