Python——爬虫

当编写一个Python爬虫时,你可以使用BeautifulSoup库来解析网页内容,使用requests库来获取网页的HTML代码。下面是一个简单的示例,演示了如何获取并解析网页内容:

python 复制代码
import requests
from bs4 import BeautifulSoup

# 发送HTTP请求获取网页内容
url = 'https://www.example.com'  # 要爬取的网页的URL
response = requests.get(url)
html_content = response.text

# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(html_content, 'html.parser')

# 提取需要的信息
title = soup.title  # 获取网页标题
links = soup.find_all('a')  # 获取所有链接

# 打印结果
print(f'网页标题:{title}')
print('所有链接:')
for link in links:
    print(link.get('href'))

上述代码中的示例网页URL为https://www.example.com,你可以将其替换为你所需爬取的网页地址。代码首先使用requests库发送HTTP GET请求获取网页内容,然后使用BeautifulSoup库解析网页内容。最后提取了网页的标题和所有链接,并打印出来。

请注意,爬取网页时需要尊重网站的使用规则,并遵守相关法律法规。

相关推荐
金銀銅鐵12 小时前
[Python] 从《千字文》中随机挑选汉字
后端·python
cup1117 小时前
[技术复盘] Windows Python 打包实战:Nuitka 环境踩坑总结与 CI 自动化构建全指南
python·ai·环境变量·ci·nuitka·skill
aqi0019 小时前
15天学会AI应用开发(七)有了大模型为什么还要引入RAG
人工智能·python·大模型·ai编程·ai应用
金銀銅鐵21 小时前
用 Python 实现 Take-Away 游戏
python·游戏
copyer_xyf1 天前
Agent 流程编排
后端·python·agent
copyer_xyf1 天前
Agent RAG
后端·python·agent
copyer_xyf1 天前
【RAG】向量数据库:milvus
后端·python·agent
copyer_xyf1 天前
Agent 记忆管理
后端·python·agent
星云穿梭2 天前
用Python写一个带图形界面的学生管理系统——完整教程
python