在现代软件开发中,网络通信是不可或缺的部分。Python 提供了强大的网络编程支持,包括 socket 通信、HTTP 请求、WebSocket 通信和爬虫技术。本章将介绍如何使用 Python 进行网络通信,并实现常见的网络编程任务。
Python 的 socket
模块可以用来实现 TCP 和 UDP 通信。
import socket
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建 TCP 套接字
server_socket.bind(("0.0.0.0", 8080)) # 绑定地址和端口
server_socket.listen(5) # 监听连接
print("等待客户端连接...")
conn, addr = server_socket.accept() # 接受客户端连接
print(f"客户端 {addr} 连接成功")
data = conn.recv(1024).decode() # 接收数据
print(f"收到数据:{data}")
conn.send("你好,客户端!".encode()) # 发送数据
conn.close()
server_socket.close()
import socket
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("127.0.0.1", 8080)) # 连接服务器
client_socket.send("Hello, Server!".encode()) # 发送数据
response = client_socket.recv(1024).decode() # 接收数据
print(f"服务器响应:{response}")
client_socket.close()
requests
模块可以方便地进行 HTTP 请求,适用于 Web 爬虫、API 调用等。
pip install requests
import requests
response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
print(response.json()) # 解析 JSON 响应
import requests
data = {"name": "Alice", "age": 25}
response = requests.post("https://httpbin.org/post", json=data)
print(response.json())
WebSocket 适用于 即时聊天、实时数据推送,可以实现双向通信。
pip install websockets
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
await websocket.send(f"收到:{message}")
start_server = websockets.serve(echo, "localhost", 8765)
asyncio.get_event_loop().run_until_complete(start_server)
asyncio.get_event_loop().run_forever()
import asyncio
import websockets
async def send_message():
async with websockets.connect("ws://localhost:8765") as websocket:
await websocket.send("你好,WebSocket!")
response = await websocket.recv()
print(f"服务器响应:{response}")
asyncio.run(send_message())
Python 爬虫可以自动获取网页数据,常用于 数据采集、自动化测试。
pip install beautifulsoup4
import requests
from bs4 import BeautifulSoup
url = "https://news.ycombinator.com/"
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
for title in soup.find_all("a", class_="storylink"):
print(title.text)
Scrapy 是功能强大的爬虫框架,适用于大规模数据采集:
pip install scrapy
创建 Scrapy 爬虫:
import scrapy
class QuotesSpider(scrapy.Spider):
name = "quotes"
start_urls = ["http://quotes.toscrape.com"]
def parse(self, response):
for quote in response.css("div.quote"):
yield {"text": quote.css("span.text::text").get()}
运行爬虫:
scrapy runspider my_spider.py -o quotes.json
本章介绍了:
requests
进行 API 调用。BeautifulSoup
和 Scrapy
进行数据采集。