import requests
from bs4 import BeautifulSoup
# 定义一个简单的网络爬虫函数,用于抓取网页内容
def simple_web_crawler(url):
# 发送HTTP请求获取网页内容
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 使用BeautifulSoup解析HTML内容
soup = BeautifulSoup(response.text, 'html.parser')
# 提取网页标题
title = soup.title.string
# 返回网页标题
return title
else:
return "Failed to retrieve the webpage"
# 示例URL
url = "https://www.example.com"
# 调用爬虫函数并打印结果
print(simple_web_crawler(url))
requests
库来发送HTTP请求,并使用 BeautifulSoup
来解析HTML内容。simple_web_crawler
函数接收一个URL作为参数,尝试抓取该网页的内容。requests.get(url)
发送GET请求,获取网页的HTML内容。BeautifulSoup
解析HTML内容,并提取网页的标题。上一篇:python with as
下一篇:python循环结构for循环
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站