利用jupyter爬取网页文字内容(无脑运行带注释,不需要的自行替换掉)

本文介绍了一个使用Python的requests库和BeautifulSoup模块从指定URL抓取网站内容的函数,处理可能出现的编码问题,并移除HTML中的<script>和<style>标签,以提供干净的HTML内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import requests
from bs4 import BeautifulSoup

def get_website_content(url):
    """
    从给定的URL抓取网站内容,保持原有格式。
    
    参数:
    url -- 要抓取的网站的URL
    
    返回:
    网站的HTML内容,如果无法抓取则返回错误信息。
    """
    try:
        # 发送HTTP GET请求到指定的URL
        response = requests.get(url)

        # 检查响应的状态码
        if response.status_code == 200:
            # 尝试使用不同的编码解码内容
            try:
                # 首先尝试使用'utf-8'编码
                content = response.content.decode('utf-8')
            except UnicodeDecodeError:
                # 如果'utf-8'解码失败,则尝试使用'gbk'编码
                content = response.content.decode('gbk')

            # 使用BeautifulSoup解析HTML内容
            soup = BeautifulSoup(content, 'html.parser')

            # 移除不必要的标签,比如<script>和<style>
            for script_or_style in soup(["script", "style"]):
                script_or_style.decompose()

            # 获取处理后的HTML内容
            cleaned_html = soup.prettify()

            return cleaned_html
        else:
            return f"Error: Unable to fetch the webpage. Status code: {response.status_code}"
    except requests.RequestException as e:
        return f"Error: An error occurred while fetching the webpage. Details: {e}"

# 替换这个URL为你想抓取的网站的URL
url = "https://www.baidu.com/"
content = get_website_content(url)

# 打印网站内容
print(content)

结果演示:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

壹万1w

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值