在数据分析和机器学习的项目中,数据的获取、清洗和处理是非常关键的步骤。今天,我们将通过一个实战案例,演示如何利用python中的beautiful soup库进行网页数据抓取,并使用pandas库进行数据清洗和处理。这个案例不仅适合初学者,也能帮助有一定经验的朋友快速掌握这两个强大的工具。
一、准备工作
在开始之前,请确保你的python环境中已经安装了requests、beautifulsoup4和pandas库。你可以通过以下命令安装它们:
pip install requests beautifulsoup4 pandas
此外,我们需要抓取一个网页的数据作为示例。为了简单起见,我们选择了一个公开的新闻网站页面。
二、抓取网页数据
首先,我们需要使用requests库获取网页的html内容。然后,使用beautiful soup解析html,并提取我们感兴趣的数据。
import requests from bs4 import beautifulsoup # 目标网页url url = 'https://example.com/news' # 替换为实际的url # 发送http请求获取网页内容 response = requests.get(url) response.raise_for_status() # 检查请求是否成功 # 使用beautiful soup解析html soup = beautifulsoup(response.text, 'html.parser')
假设我们要提取新闻标题、发布时间和正文内容。通过检查网页的html结构,我们发现这些信息都包含在特定的html标签中。
# 提取新闻标题、发布时间和正文内容 articles = [] for article in soup.select('.news-article'): # 假设新闻文章都有class="news-article" title = article.select_one('h2.title').text.strip() publish_time = article.select_one('.publish-time').text.strip() content = article.select_one('.content').text.strip() articles.append({ 'title': title, 'publish_time': publish_time, 'content': content })
三、数据清洗
抓取到的数据通常包含一些不需要的信息,比如多余的空格、html标签残留、特殊字符等。我们需要对这些数据进行清洗。
import pandas as pd # 将数据转换为dataframe df = pd.dataframe(articles) # 打印前几行数据查看 print(df.head()) # 数据清洗步骤 # 1. 去除字符串前后的空格(已在提取时处理) # 2. 替换特殊字符(例如换行符为空格) df['content'] = df['content'].str.replace('\n', ' ') # 3. 删除缺失值或无效数据(假设空标题或空内容的数据无效) df = df.dropna(subset=['title', 'content']) # 4. 统一时间格式(假设发布时间为"yyyy-mm-dd hh:mm:ss"格式) # 这里我们假设发布时间已经是字符串格式,且格式统一,如果需要转换格式,可以使用pd.to_datetime() # df['publish_time'] = pd.to_datetime(df['publish_time'], format='%y-%m-%d %h:%m:%s') # 打印清洗后的数据查看 print(df.head())
四、数据处理
数据清洗后,我们可能还需要进行一些额外的处理,比如数据转换、数据合并、数据分组等。
# 数据处理步骤 # 1. 提取发布日期的日期部分(如果需要) # df['publish_date'] = df['publish_time'].dt.date # 2. 统计每个发布日期的新闻数量(如果需要) # daily_counts = df['publish_date'].value_counts().reset_index() # daily_counts.columns = ['publish_date', 'count'] # print(daily_counts) # 3. 根据关键词过滤新闻(例如只保留包含"疫情"关键词的新闻) keyword = '疫情' filtered_df = df[df['content'].str.contains(keyword, na=false, case=false)] # 打印过滤后的数据查看 print(filtered_df.head())
五、保存数据
处理完数据后,我们可能需要将其保存到文件中,以便后续使用。pandas提供了多种保存数据的方法,比如保存为csv文件、excel文件等。
# 保存数据为csv文件 csv_file_path = 'cleaned_news_data.csv' df.to_csv(csv_file_path, index=false, encoding='utf-8-sig') # 保存数据为excel文件 excel_file_path = 'cleaned_news_data.xlsx' df.to_excel(excel_file_path, index=false, engine='openpyxl')
六、完整代码示例
为了方便大家理解和运行,以下是完整的代码示例。请确保将url变量替换为实际的网页url,并根据实际的html结构调整beautiful soup的选择器。
import requests from bs4 import beautifulsoup import pandas as pd # 目标网页url(请替换为实际的url) url = 'https://example.com/news' # 发送http请求获取网页内容 response = requests.get(url) response.raise_for_status() # 使用beautiful soup解析html soup = beautifulsoup(response.text, 'html.parser') # 提取新闻标题、发布时间和正文内容 articles = [] for article in soup.select('.news-article'): # 假设新闻文章都有class="news-article" title = article.select_one('h2.title').text.strip() publish_time = article.select_one('.publish-time').text.strip() content = article.select_one('.content').text.strip() articles.append({ 'title': title, 'publish_time': publish_time, 'content': content }) # 将数据转换为dataframe df = pd.dataframe(articles) # 数据清洗步骤 df['content'] = df['content'].str.replace('\n', ' ') df = df.dropna(subset=['title', 'content']) # 数据处理步骤(示例:根据关键词过滤新闻) keyword = '疫情' filtered_df = df[df['content'].str.contains(keyword, na=false, case=false)] # 保存数据为csv文件和excel文件 csv_file_path = 'cleaned_news_data.csv' excel_file_path = 'cleaned_news_data.xlsx' df.to_csv(csv_file_path, index=false, encoding='utf-8-sig') df.to_excel(excel_file_path, index=false, engine='openpyxl') # 打印过滤后的数据查看 print(filtered_df.head())
七、总结
通过本文,我们学会了如何使用beautiful soup进行网页数据抓取,并使用pandas进行数据清洗和处理。这两个库的结合使用可以大大提高我们处理网页数据的效率。在实际项目中,你可能需要根据具体的网页结构和数据需求调整代码。希望这个实战案例能帮助你更好地掌握这两个工具,并在你的数据分析和机器学习项目中发挥它们的作用。
到此这篇关于使用beautifulsoup和pandas进行网页数据抓取与清洗处理的文章就介绍到这了,更多相关beautifulsoup pandas数据抓取与清洗内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论