import requests
from bs4 import BeautifulSoup
# 定义一个函数来爬取网页数据
def fetch_web_data(url):
try:
# 发送HTTP请求获取网页内容
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
# 示例:提取所有标题标签<h1>的内容
titles = soup.find_all('h1')
# 打印所有标题
for title in titles:
print(title.get_text())
else:
print(f"请求失败,状态码: {response.status_code}")
except Exception as e:
print(f"发生错误: {e}")
# 示例URL
url = 'https://example.com'
fetch_web_data(url)
导入库:
requests:用于发送HTTP请求并获取网页内容。BeautifulSoup:用于解析HTML文档,方便提取所需的数据。定义函数 fetch_web_data:
requests.get()方法发送HTTP GET请求,获取网页内容。BeautifulSoup解析HTML文档,并提取所有<h1>标签的内容。异常处理:
示例URL:
https://example.com作为示例URL,你可以替换为你想要爬取的实际网址。上一篇:python jieba库
下一篇:pythonrange函数
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站