import requests
from bs4 import BeautifulSoup
# 定义一个函数来爬取网页内容
def fetch_webpage(url):
try:
# 发送HTTP请求获取网页内容
response = requests.get(url)
# 检查请求是否成功
if response.status_code == 200:
# 使用BeautifulSoup解析网页内容
soup = BeautifulSoup(response.text, 'html.parser')
return soup.prettify() # 返回格式化后的HTML内容
else:
return f"Error: Unable to fetch webpage. Status code: {response.status_code}"
except Exception as e:
return f"Error: {str(e)}"
# 示例URL
url = "https://example.com"
# 调用函数并打印结果
print(fetch_webpage(url))
导入库:
requests:用于发送HTTP请求。BeautifulSoup:用于解析HTML内容。定义函数 fetch_webpage:
requests.get()发送HTTP GET请求。BeautifulSoup解析HTML内容,并返回格式化后的HTML字符串。示例调用:
https://example.com)。fetch_webpage函数并打印结果。上一篇:python中等待几秒代码
下一篇:python空格
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站