# 导入所需的库
import requests
from bs4 import BeautifulSoup
# 定义一个函数来爬取网页信息
def fetch_webpage(url):
# 发送HTTP请求获取网页内容
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
# 示例:提取所有的标题标签<h1>
titles = soup.find_all('h1')
for title in titles:
print(title.get_text())
else:
print("请求失败,状态码:", response.status_code)
# 调用函数并传入目标URL
if __name__ == "__main__":
url = "https://example.com" # 替换为你要爬取的网址
fetch_webpage(url)
requests 库发送HTTP请求,BeautifulSoup 用于解析HTML内容。fetch_webpage 函数接收一个URL作为参数。requests.get() 方法获取网页内容。BeautifulSoup 解析HTML,并提取所有 <h1> 标签的内容。如果你需要爬取其他特定的信息,可以根据需求修改 soup.find_all() 的参数。
上一篇:c++与python的区别
下一篇:python json 转字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站