Python的秘密基地--[章节16] Python 网络编程

第16章:Python 网络编程

在现代软件开发中,网络通信是不可或缺的部分。Python 提供了强大的网络编程支持,包括 socket 通信、HTTP 请求、WebSocket 通信和爬虫技术。本章将介绍如何使用 Python 进行网络通信,并实现常见的网络编程任务。


16.1 网络编程基础

16.1.1 网络通信协议

  • TCP(Transmission Control Protocol):面向连接的可靠传输协议,适用于 HTTP、FTP 等。
  • UDP(User Datagram Protocol):无连接、快速但不可靠,适用于视频流、实时通信等。

16.2 使用 socket 进行网络通信

Python 的 socket 模块可以用来实现 TCP 和 UDP 通信。

16.2.1 创建 TCP 服务器

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()

16.2.2 创建 TCP 客户端

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()

16.3 处理 HTTP 请求(requests 模块)

requests 模块可以方便地进行 HTTP 请求,适用于 Web 爬虫、API 调用等。

16.3.1 安装 requests

pip install requests

16.3.2 发送 GET 请求

import requests

response = requests.get("https://jsonplaceholder.typicode.com/todos/1")
print(response.json())  # 解析 JSON 响应

16.3.3 发送 POST 请求

import requests

data = {"name": "Alice", "age": 25}
response = requests.post("https://httpbin.org/post", json=data)
print(response.json())

16.4 WebSocket 通信

WebSocket 适用于 即时聊天、实时数据推送,可以实现双向通信。

16.4.1 安装 WebSocket 库

pip install websockets

16.4.2 创建 WebSocket 服务器

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()

16.4.3 创建 WebSocket 客户端

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())

16.5 Python 网络爬虫

Python 爬虫可以自动获取网页数据,常用于 数据采集、自动化测试

16.5.1 使用 BeautifulSoup 解析 HTML

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)

16.5.2 使用 Scrapy 进行爬取

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

16.6 小结

本章介绍了:

  • socket 通信:实现 TCP 服务器和客户端。
  • HTTP 请求:使用 requests 进行 API 调用。
  • WebSocket 通信:实现实时双向通信。
  • 网络爬虫:使用 BeautifulSoupScrapy 进行数据采集。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码上有潜

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值