Python爬虫技术 第23节 数据清洗和预处理

news2024/9/19 9:50:42

在使用Python进行网络爬虫项目时,数据清洗和预处理是非常重要的步骤。这些步骤有助于确保从网页上抓取的数据准确、一致,并且适合后续的分析或机器学习任务。下面我将详细介绍如何使用Python来进行数据清洗和预处理。

在这里插入图片描述

1. 数据获取

首先,你需要使用爬虫技术来获取数据。Python中有许多库可以帮助你完成这项工作,比如requests用于发送HTTP请求,BeautifulSouplxml用于解析HTML文档,以及Scrapy框架用于更复杂的爬虫项目。

示例代码:
import requests
from bs4 import BeautifulSoup

url = "https://example.com"
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')

# 假设我们要提取所有的文章标题
titles = [title.get_text() for title in soup.find_all('h1')]

2. 数据清洗

一旦数据被提取出来,就需要进行清洗。常见的数据清洗任务包括去除HTML标签、处理缺失值、去除重复项等。

示例代码:
# 去除多余的空格
cleaned_titles = [title.strip() for title in titles]

# 去除重复项
unique_titles = list(set(cleaned_titles))

3. 数据预处理

数据预处理通常涉及转换数据格式、标准化数据、填充缺失值等操作。

示例代码:
# 转换为小写
lowercase_titles = [title.lower() for title in unique_titles]

# 填充缺失值(如果有的话)
# 假设我们有一个包含其他字段的字典列表
data = [{'title': title, 'content': ''} for title in lowercase_titles]
for item in data:
    if not item['content']:
        item['content'] = 'No content available.'

4. 文本预处理

对于文本数据,你可能还需要执行一些特定的预处理步骤,例如分词、去除停用词、词干化等。

示例代码:
import nltk
from nltk.corpus import stopwords
from nltk.stem import PorterStemmer

nltk.download('stopwords')
nltk.download('punkt')

stemmer = PorterStemmer()
stop_words = set(stopwords.words('english'))

def preprocess_text(text):
    tokens = nltk.word_tokenize(text)
    filtered_tokens = [stemmer.stem(word) for word in tokens if word.isalpha() and word not in stop_words]
    return ' '.join(filtered_tokens)

preprocessed_titles = [preprocess_text(title) for title in lowercase_titles]

5. 存储与分析

最后一步是存储这些数据以供进一步分析。你可以将数据保存到CSV文件、数据库或者直接用于建模。

示例代码:
import pandas as pd

df = pd.DataFrame(preprocessed_titles, columns=['Title'])
df.to_csv('titles.csv', index=False)

以上步骤提供了从数据获取到预处理的基本流程。根据具体的需求,你可能需要调整这些步骤。如果你有更具体的问题或者需要进一步的帮助,请告诉我!

让我们继续扩展上面提到的代码示例,这次我们将添加更多的细节,包括异常处理、日志记录以及更完整的文本预处理步骤。以下是完整的代码实现:

首先,我们需要安装必要的库,如nltk。可以通过以下命令安装:

pip install nltk
pip install beautifulsoup4
pip install requests
pip install pandas

接下来是具体的代码实现:

import requests
from bs4 import BeautifulSoup
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
import pandas as pd
import logging

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 下载NLTK资源
nltk.download('stopwords')
nltk.download('punkt')

# 设置URL
url = "https://example.com"

# 发送HTTP请求并解析HTML
def fetch_html(url):
    try:
        response = requests.get(url)
        response.raise_for_status()  # 检查响应状态
        return response.text
    except requests.RequestException as e:
        logging.error(f"Error fetching URL: {e}")
        return None

# 解析HTML并提取数据
def parse_html(html):
    soup = BeautifulSoup(html, 'html.parser')
    # 假设我们想要提取所有的文章标题
    titles = [title.get_text() for title in soup.find_all('h1')]
    return titles

# 清洗数据
def clean_data(titles):
    cleaned_titles = [title.strip() for title in titles]  # 移除首尾空白
    unique_titles = list(set(cleaned_titles))  # 去重
    return unique_titles

# 文本预处理
def preprocess_text(titles):
    stemmer = PorterStemmer()
    stop_words = set(stopwords.words('english'))
    
    preprocessed_titles = []
    for title in titles:
        tokens = word_tokenize(title)
        filtered_tokens = [stemmer.stem(word) for word in tokens if word.isalpha() and word.lower() not in stop_words]
        preprocessed_titles.append(' '.join(filtered_tokens))
    return preprocessed_titles

# 将数据保存到CSV文件
def save_to_csv(data, filename):
    df = pd.DataFrame(data, columns=['Title'])
    df.to_csv(filename, index=False)

# 主程序
def main():
    html = fetch_html(url)
    if html is not None:
        titles = parse_html(html)
        if titles:
            logging.info("Titles extracted successfully.")
            unique_titles = clean_data(titles)
            preprocessed_titles = preprocess_text(unique_titles)
            save_to_csv(preprocessed_titles, 'titles.csv')
            logging.info("Data saved to CSV.")
        else:
            logging.warning("No titles found.")
    else:
        logging.error("Failed to fetch HTML.")

if __name__ == "__main__":
    main()

这段代码包含了以下几个部分:

  1. 日志配置:使用logging模块记录程序运行过程中的信息。
  2. 异常处理:通过try-except块来捕获和处理可能出现的错误。
  3. 数据获取:使用requests库发送HTTP请求并获取HTML内容。
  4. 数据解析:使用BeautifulSoup解析HTML并提取数据。
  5. 数据清洗:去除空白字符和重复项。
  6. 文本预处理:分词、去除停用词和词干化。
  7. 数据保存:使用pandas将处理后的数据保存到CSV文件中。

这个脚本可以作为一个完整的示例,用来抓取网站上的数据并进行基本的清洗和预处理。你可以根据实际需求调整URL、要提取的元素类型以及其他参数。

我们可以进一步优化代码的功能,比如增加更多的异常处理、日志记录以及更详细的文本预处理步骤。此外,我们还可以加入一个简单的用户界面来控制爬虫的行为,比如指定要抓取的页面数量。

下面是基于之前的代码进一步扩展的例子:

import requests
from bs4 import BeautifulSoup
import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.stem import PorterStemmer
import pandas as pd
import logging
from urllib.parse import urljoin

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

# 下载NLTK资源
nltk.download('stopwords')
nltk.download('punkt')

# 设置URL
base_url = "https://example.com"

# 发送HTTP请求并解析HTML
def fetch_html(url):
    try:
        response = requests.get(url)
        response.raise_for_status()  # 检查响应状态
        return response.text
    except requests.RequestException as e:
        logging.error(f"Error fetching URL: {url} - {e}")
        return None

# 解析HTML并提取数据
def parse_html(html, base_url):
    soup = BeautifulSoup(html, 'html.parser')
    # 假设我们想要提取所有的文章标题
    titles = [title.get_text() for title in soup.find_all('h1')]
    # 获取所有链接
    links = [urljoin(base_url, link.get('href')) for link in soup.find_all('a') if link.get('href')]
    return titles, links

# 清洗数据
def clean_data(titles):
    cleaned_titles = [title.strip() for title in titles]  # 移除首尾空白
    unique_titles = list(set(cleaned_titles))  # 去重
    return unique_titles

# 文本预处理
def preprocess_text(titles):
    stemmer = PorterStemmer()
    stop_words = set(stopwords.words('english'))
    
    preprocessed_titles = []
    for title in titles:
        tokens = word_tokenize(title)
        filtered_tokens = [stemmer.stem(word) for word in tokens if word.isalpha() and word.lower() not in stop_words]
        preprocessed_titles.append(' '.join(filtered_tokens))
    return preprocessed_titles

# 将数据保存到CSV文件
def save_to_csv(data, filename):
    df = pd.DataFrame(data, columns=['Title'])
    df.to_csv(filename, index=False)

# 主程序
def main(max_pages=1):
    visited_links = set()
    titles = []

    def crawl_page(url):
        if url in visited_links:
            return
        visited_links.add(url)
        html = fetch_html(url)
        if html is not None:
            page_titles, page_links = parse_html(html, base_url)
            titles.extend(page_titles)
            for link in page_links:
                if len(visited_links) < max_pages:
                    crawl_page(link)

    crawl_page(base_url)

    if titles:
        logging.info("Titles extracted successfully.")
        unique_titles = clean_data(titles)
        preprocessed_titles = preprocess_text(unique_titles)
        save_to_csv(preprocessed_titles, 'titles.csv')
        logging.info("Data saved to CSV.")
    else:
        logging.warning("No titles found.")

if __name__ == "__main__":
    # 用户可以指定要爬取的最大页面数
    max_pages = 5
    main(max_pages)

在这个版本中,我们做了以下改进:

  1. 递归爬取:现在脚本可以递归地爬取多个页面。max_pages 参数控制最大爬取页面数。
  2. 链接处理:使用 urljoin 函数来正确构建绝对URL。
  3. 用户输入:允许用户指定要爬取的最大页面数。

这样,脚本不仅可以抓取初始页面的数据,还可以探索其他相关页面,收集更多数据。请注意,在实际应用中,递归爬取可能会遇到网站的robots.txt规则限制或其他访问限制,因此在部署时请确保遵守网站的爬虫政策。

如果您有其他具体需求或想进一步扩展功能,请随时告知!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1970815.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

Java 实现 AVL树

在二叉平衡树中&#xff0c;我们进行插入和删除操作时都需要遍历树&#xff0c;可见树的结构是很影响操作效率的。在最坏的情况下&#xff0c;树成了一个单支树&#xff0c;查找的时间复杂度成了O(N)&#xff0c;建树跟没建树一样。那么是不是有什么办法可以建一个树避免这种情…

基于 KubeSphere 的 Kubernetes 生产环境部署架构设计及成本分析

转载&#xff1a;基于 KubeSphere 的 Kubernetes 生产环境部署架构设计及成本分析 前言 导图 1. 简介 1.1 架构概要说明 今天分享一个实际小规模生产环境部署架构设计的案例&#xff0c;该架构设计概要说明如下&#xff1a; 本架构设计适用于中小规模(<50)的 Kubernetes …

本地生活服务商公司有哪些?一文教你搭建本地生活系统!

当前&#xff0c;本地生活领域群雄环伺&#xff0c;日益激烈的竞争推动各家互联网大厂调整布局模式的同时&#xff0c;也让本地生活市场持续迸发新的活力。在此背景下&#xff0c;想要通过本地生活服务商身份入局的创业者数量不断增多&#xff0c;以本地生活服务商公司有哪些等…

前端面试题整理-CSS

两栏布局 <!DOCTYPE html> <html lang"en"><head><meta charset"UTF-8" /><meta name"viewport" content"widthdevice-width, initial-scale1.0" /><title>两栏布局</title><style>…

java计算机毕设课设—基于网络爬虫技术的网络新闻分析系统(附源码、文章、相关截图、部署视频)

这是什么系统&#xff1f; java计算机毕设课设—基于网络爬虫技术的网络新闻分析系统 基于网络爬虫技术的新闻分析系统&#xff0c;它能够实时抓取凤凰网、网易、新浪、搜狐等网站的新闻数据&#xff0c;提取正文和点击量&#xff0c;每日定时抓取。系统还能对抓取的新闻进行…

给echarts图表线条、数据点和区域设置颜色

let myChart echarts.init(document.getElementById("chartmainCop"));// 获取当前干部的各项评分const allIndicators Object.keys(this.dialogEacherTable[0]).filter(key > key ! "CadreID" && key ! "xm").map(key > ({name…

window电脑上使用python将pdf转换为word文档

1、电脑上安装Python运行环境 一、python官网下载链接 二、下载到电脑后&#xff0c;直接运行安装 三、安装完成后按&#xff1a;winR键进入window命令控制窗口&#xff0c;输入 python --version2、设置python依赖包国内镜像源 pip config set global.index-url https://mirr…

国家发改委区域司韩振海副司长一行莅临麒麟信安调研

7月31日&#xff0c;国家发改委区域司韩振海副司长一行莅临麒麟信安调研。湖南省发改委区域处处长孙健军&#xff0c;长沙市发改委党组成员、市长株潭一体化发展事务中心主任邹犇淼等相关领导陪同调研。麒麟信安总裁刘文清热情接待。 在麒麟信安展厅&#xff0c;韩振海副司长一…

在MANET中的TCP增强

本文内容节选自一篇系统性文献综述&#xff08;Systematic Literature Review, SLR&#xff09;&#xff0c;标题为“TCP Performance Enhancement in IoT and MANET”&#xff0c;由 Sultana Parween 和 Syed Zeeshan Hussain 撰写&#xff0c;发表在《International Journal …

Windows下Rust OpenCV环境配置

首发于Enaium的个人博客 安装Chocolatey 首先我们需要安装Chocolatey&#xff0c;Chocolatey是一个Windows的包管理器。 我们点击右上角的Install进入到Installing Chocolatey&#xff0c;选择Individual 复制命令 Set-ExecutionPolicy Bypass -Scope Process -Force; [Sys…

springboot餐饮管理系统-计算机毕业设计源码73168

摘要 随着科技的不断进步和互联网时代的深入发展&#xff0c;餐饮行业正面临着一场由传统向智能化、信息化转变的革命。传统的餐饮管理方式&#xff0c;如手工点餐、纸质菜单、人工结算等&#xff0c;已经无法满足现代餐饮企业对于效率、准确性和用户体验的高要求。因此&#x…

【Hot100】LeetCode—31. 下一个排列

目录 题目1- 思路2- 实现⭐31. 下一个排列——题解思路 3- ACM 实现 题目 原题连接&#xff1a;31. 下一个排列 1- 思路 技巧题&#xff0c;分为以下几个步骤 ① 寻找拐点&#xff1a; i 1 &#xff1a;出现 nums[i1] > nums[i] &#xff0c;则 i 1 就是拐点 从右向左遍…

技术守护尊严||Chat GPT在抵抗性骚扰的作用分析

就在本周&#xff0c;中国人民大学女博士实名举报导师性骚扰的事情&#xff0c;引发全网关注&#xff01; 性骚扰&#xff0c;无论在线上还是线下&#xff0c;无论在职场还是校园&#xff0c;都是对个人尊严与权益的严重侵犯。 幸运的是&#xff0c;随着人工智能技术的飞速发…

专题九_链表(1)

目录 题型总结 2. 两数相加 解析 题解 24. 两两交换链表中的节点 解析 题解 题型总结 2. 两数相加 2. 两数相加 解析 题解 /*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr)…

硬件开发笔记(二十九):TPS54331电源设计(二):12V转3.3V和12V转4V原理图设计

若该文为原创文章&#xff0c;转载请注明原文出处 本文章博客地址&#xff1a;https://hpzwl.blog.csdn.net/article/details/140868749 长沙红胖子Qt&#xff08;长沙创微智科&#xff09;博文大全&#xff1a;开发技术集合&#xff08;包含Qt实用技术、树莓派、三维、OpenCV…

一款功能强大且免费的跨平台图片批量处理工具

XnConvert是一款功能强大且免费的跨平台图片批量处理工具&#xff0c;广泛应用于个人用户、教育机构和非营利组织。它支持超过500种图片格式&#xff0c;包括常见的JPEG、PNG、TIFF、GIF、WebP、PSD、JPEG2000等&#xff0c;并能够导出为大约70种不同的文件格式。 该软件的主要…

【云原生】kubernetes弃用docker之后,containerd何以承载云原生?

✨✨ 欢迎大家来到景天科技苑✨✨ &#x1f388;&#x1f388; 养成好习惯&#xff0c;先赞后看哦~&#x1f388;&#x1f388; &#x1f3c6; 作者简介&#xff1a;景天科技苑 &#x1f3c6;《头衔》&#xff1a;大厂架构师&#xff0c;华为云开发者社区专家博主&#xff0c;…

Mac OS平台,利用 gifify 制作gif教程

一、前言 在很多时候都会用到视频的方式才能直观的表达想表达的东西&#xff0c; 但是视频的文件太大了&#xff0c;所以gif是一个很不错的选择&#xff0c;在网上找了很多免费的都不好用&#xff0c; 最理想的还是直接快捷键唤起&#xff0c;然后选择录制区域&#xff0c;保存…

[CR]厚云填补_GridDehazeNet

GridDehazeNet: Attention-Based Multi-Scale Network for Image Dehazing Abstract 我们提出了一个端到端的可训练卷积神经网络(CNN)&#xff0c;命名为GridDehazeNet&#xff0c;用于单幅图像去雾。GridDehazeNet由预处理、主干网络和后处理三个模块组成。与手工选择的预处理…

Go语言---linux下安装golang protoc详细教程以及完整安装protoc-gen-go工具

在[分布式网络通讯框架]----Protobuf安装配置–附带每一步截图中&#xff0c;我们详细介绍了Protobuf是什么&#xff0c;为什么要使用Protobuf&#xff0c;以及在linux环境中&#xff0c;如何安装Protobuf。Protobuf 在 .proto 定义需要处理的结构化数据&#xff0c;可以通过 p…