Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

python获取网页数据

作者:余烬已熄   发布日期:2025-03-21   浏览:94

import requests

# 使用requests库来获取网页数据
def get_webpage_data(url):
    try:
        # 发送HTTP GET请求
        response = requests.get(url)
        # 检查请求是否成功
        if response.status_code == 200:
            # 返回网页内容
            return response.text
        else:
            return f"Error: Unable to retrieve data, status code {response.status_code}"
    except Exception as e:
        return f"Error: {str(e)}"

# 示例URL
url = "https://www.example.com"
# 获取网页数据
webpage_content = get_webpage_data(url)
print(webpage_content)

解释说明:

  1. 导入库:我们使用 requests 库来发送HTTP请求并获取网页内容。
  2. 定义函数get_webpage_data(url) 函数接收一个URL作为参数,并尝试获取该URL的网页内容。
  3. 发送请求:使用 requests.get(url) 发送GET请求。
  4. 检查状态码:如果响应的状态码是200,表示请求成功,返回网页内容;否则返回错误信息。
  5. 异常处理:使用 try-except 块捕获可能发生的异常,并返回相应的错误信息。
  6. 示例调用:通过一个示例URL调用该函数,并打印返回的网页内容。

希望这段代码和解释对你有帮助!

上一篇:python 数组添加

下一篇:遍历python

大家都在看

python时间格式

python ord和chr

python list.pop

python的for i in range

npm config set python

python代码简单

python读取文件夹

python中turtle

python 输出时间

python中list代表什么

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站