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

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
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
当使用Jupyter进行微博关键词爬取时,你可以按照以下步骤进行操作: 1. 安装必要的库:首先,你需要安装Python的requests、beautifulsoup4和pandas库。你可以使用以下命令来安装它们: ``` pip install requests beautifulsoup4 pandas ``` 2. 导入所需的库:在Jupyter Notebook中,你需要导入这些库以便使用它们。使用以下代码导入它们: ```python import requests from bs4 import BeautifulSoup import pandas as pd ``` 3. 发送请求并解析页面:使用requests库发送HTTP请求,并使用BeautifulSoup库解析返回的HTML页面。以下是一个示例代码: ```python # 发送请求 url = 'https://s.weibo.com/weibo?q=关键词' response = requests.get(url) # 解析页面 soup = BeautifulSoup(response.text, 'html.parser') ``` 请将"关键词"替换为你要搜索的实际关键词。 4. 提取所需信息:根据页面的HTML结构,使用BeautifulSoup库提取你需要的信息。例如,如果你想提取微博的文本内容和发布时间,可以使用以下代码: ```python # 提取微博内容和发布时间 weibo_list = soup.find_all('div', class_='content') for weibo in weibo_list: text = weibo.find('p').text.strip() time = weibo.find('p', class_='from').find('a').text.strip() print(text, time) ``` 5. 存储数据:如果你想将提取的数据保存到文件中,可以使用pandas库将数据转换为DataFrame,并将其保存为CSV文件。以下是一个示例代码: ```python # 创建DataFrame并保存为CSV文件 data = {'Text': [], 'Time': []} for weibo in weibo_list: text = weibo.find('p').text.strip() time = weibo.find('p', class_='from').find('a').text.strip() data['Text'].append(text) data['Time'].append(time) df = pd.DataFrame(data) df.to_csv('weibo_data.csv', index=False) ``` 请确保你已经创建了一个名为"weibo_data.csv"的文件。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

壹万1w

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

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

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

打赏作者

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

抵扣说明:

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

余额充值