Python侦探:我用代码破解男朋友的浏览历史,发现了惊天秘密!

夜深了,窗外的风带着寒意,屋内却充满了迷人的神秘氛围。你知道的,他最近总是神神秘秘地盯着电脑屏幕,嘴角挂着不可言说的微笑。而当你走近,他就像触电一样迅速切换页面,仿佛你刚才看到的内容对他来说有着致命的吸引力。你隐隐感到,有什么不对劲------他到底在看什么?

你决定,不能再被蒙在鼓里了。你深吸一口气,打开电脑,敲击键盘,这一次,你要用Python脚本分析他的浏览记录,看看他到底在偷偷浏览些什么不可告人的秘密。🕵️‍♀️

第一章:破解浏览记录的密码

你首先开始了最基础的工作------寻找谷歌浏览器的历史记录文件。通过搜索和查阅资料,你终于锁定了谷歌浏览器的历史记录文件存储路径。你兴奋地打开了路径,发现原来他的所有浏览记录都被悄无声息地保存在那座名为 History 的数据库里。

你用 sqlite3 库,轻松地打开了这个数据库文件,开始提取历史记录中的关键数据------URL、网页标题、访问次数等。你毫不费力地获取了这些信息,就像打开了密码锁的一把钥匙。你开始分析这些数据,心中升起了一丝不安:到底是哪些网站让他如此神魂颠倒?

python 复制代码
import sqlite3

# 获取浏览器历史记录数据库路径
history_path = r"C:\Users\你的用户名\AppData\Local\Google\Chrome\User Data\Default\History"

# 连接到历史记录数据库
conn = sqlite3.connect(history_path)
cursor = conn.cursor()

# 查询访问历史
cursor.execute("SELECT url, title, visit_count FROM urls")
rows = cursor.fetchall()

# 打印历史记录
for row in rows:
    print(row)

# 关闭数据库连接
conn.close()

在输出的记录中,你发现了一个奇怪的现象------他的浏览历史中充满了关于某些特定网站的访问记录。你不禁开始怀疑,这些网页背后究竟隐藏着什么秘密?你决定统计下他访问最多的前10个网站,看看这些网站背后究竟有怎样的真相。

python 复制代码
import sqlite3
import os
from urllib.parse import urlparse
from collections import Counter


def get_top_10_domains():
    # 获取用户目录
    user_profile = os.getenv('USERPROFILE')
    # 构建历史记录数据库的完整路径
    history_path = os.path.join(user_profile, r'AppData\Local\Google\Chrome\User Data\Default\History')
    domain_counts = Counter()
    try:
        # 连接历史记录数据库
        conn = sqlite3.connect(history_path)
        cursor = conn.cursor()
        # 执行 SQL 查询,从 urls 表中获取 url 信息
        cursor.execute("SELECT url FROM urls")
        results = cursor.fetchall()
        for result in results:
            url = result[0]
            # 解析 url 获取域名
            domain = urlparse(url).netloc
            if domain:
                domain_counts[domain] += 1
    except sqlite3.Error as e:
        print(f"SQLite error occurred: {e}")
    finally:
        # 关闭数据库连接
        conn.close()
    # 获取前 10 大访问量最多的域名
    top_10_domains = domain_counts.most_common(10)
    for i, (domain, count) in enumerate(top_10_domains):
        print(f"{i + 1}.  {domain}, Count: {count}")


if __name__ == "__main__":
    get_top_10_domains()

通过 Python 代码,你快速地统计了每个网站的访问次数,结果让你大吃一惊------他竟然频繁访问了这些网站,访问次数最多的前10个网站如下:

bash 复制代码
1.  mp.weixin.qq.com, Count: 453
2.  image.baidu.com, Count: 436
3.  www.baidu.com, Count: 323
4.  www.bilibili.com, Count: 306
5.  douyin.com, Count: 260
6.  github.com, Count: 113
7.  juejin.cn, Count: 94
8.  jd.com, Count: 89
9.  www.taobao.com, Count: 68
10.  dev.epicgames.com, Count: 65

这都是些常见的网站,并没有发现异常情况,你决定进一步分析,看看他的兴趣究竟在哪里。

第二章:情感分析------窥探他的心情

作为一名程序员,你知道,要揭开一个人的秘密,仅仅查看访问记录是不够的。你需要更深入地了解每个网页背后蕴藏的情感------也许,某个网页的标题透露出了他那隐藏的情感倾向。

你拿起你的编程工具,调用 jieba 进行中文分词,然后利用 SnowNLP 做情感分析。你开始解密每个网页标题的情感波动,心情是激动还是消沉?结果,让你大吃一惊------原来这些网页带有极强的情感倾向,或喜悦、或愤怒,甚至有些网页标题背后隐藏着某种无法言喻的情感暗流。

python 复制代码
import sqlite3
import os
import jieba
from snownlp import SnowNLP
import numpy as np


def analyze_sentiment():
    # 获取用户目录
    user_profile = os.getenv('USERPROFILE')
    # 构建历史记录数据库的完整路径
    history_path = os.path.join(user_profile, r'AppData\Local\Google\Chrome\User Data\Default\History')
    positive_count = 0
    negative_count = 0
    neutral_count = 0
    sentiment_scores = []
    try:
        # 连接历史记录数据库
        conn = sqlite3.connect(history_path)
        cursor = conn.cursor()
        # 执行 SQL 查询,从 urls 表中获取 title 信息
        cursor.execute("SELECT title FROM urls")
        results = cursor.fetchall()
        for result in results:
            title = result[0]
            if title:
                # 使用 jieba 分词
                words = jieba.cut(title)
                title_text = " ".join(words)
                # 使用 SnowNLP 进行情感分析
                s = SnowNLP(title_text)
                sentiment_score = s.sentiments
                sentiment_scores.append(sentiment_score)
                if sentiment_score > 0.6:
                    positive_count += 1
                elif sentiment_score < 0.4:
                    negative_count += 1
                else:
                    neutral_count += 1
    except sqlite3.Error as e:
        print(f"SQLite error occurred: {e}")
    finally:
        # 关闭数据库连接
        conn.close()
    # 计算平均情感得分
    if sentiment_scores:
        average_score = np.mean(sentiment_scores)
    else:
        average_score = 0
    # 生成报告
    print("情感分析报告:")
    print(f"平均情感得分: {average_score}")
    print(f"积极情感的标题数量: {positive_count}")
    print(f"消极情感的标题数量: {negative_count}")
    print(f"中性情感的标题数量: {neutral_count}")


if __name__ == "__main__":
    analyze_sentiment()

也许是你多想了,通过计算你得知,平均情感得分是 0.65,这个得分表明整体上男朋友访问页面的标题所传达出的情感倾向是较为积极的。

bash 复制代码
情感分析报告:
平均情感得分: 0.6503623448873965
积极情感的标题数量: 2256
消极情感的标题数量: 712
中性情感的标题数量: 1439

第三章:揭示真相------用词云揭开秘密

情感分析的结果让你更加强烈地感受到一种神秘的情绪波动。于是,你决定利用 jieba 分词提取网页标题中的关键词,生成一个词云图。通过这些词云图,你希望找到访问频率最高的词语,看看男朋友的心里到底有什么"秘密"在萌动。

你去掉了所有的无意义词汇,比如"了"、"的"和"么"等,只保留了那些能够反映兴趣的关键词。你开始生成词云图,期待着看到某些特别的词语在图中"跃然纸上"。这些词,或许正是解开这个谜团的关键。

python 复制代码
import sqlite3
import os
import jieba
from wordcloud import WordCloud
import matplotlib.pyplot as plt
import numpy as np
from PIL import Image


def get_titles():
    user_profile = os.getenv('USERPROFILE')
    history_path = os.path.join(user_profile, r'AppData\Local\Google\Chrome\User Data\Default\History')
    titles = []
    try:
        conn = sqlite3.connect(history_path)
        cursor = conn.cursor()
        cursor.execute("SELECT title FROM urls")
        results = cursor.fetchall()
        for result in results:
            title = result[0]
            if title:
                titles.append(title)
    except sqlite3.Error as e:
        print(f"SQLite error occurred: {e}")
    finally:
        conn.close()
    return titles


def load_stopwords():
    stopwords = {"了", "的", "么", "是", "在", "有", "和", "就", "都", "而", 
    "及", "与", "也", "很", "并", "之", "其", "此", "但", "一个", "一些"}
    return stopwords
    
def process_titles(titles):
    stopwords = load_stopwords()
    all_words = []
    for title in titles:
        words = jieba.cut(title)
        for word in words:
            if word not in stopwords:
                all_words.append(word)
    return all_words


def generate_wordcloud(words):
    # 设置词云的形状为 16:9 的长方形
    width = 1600
    height = 900
    mask = np.zeros((height, width), np.uint8)
    wordcloud = WordCloud(width=width, height=height, background_color='white', 
                          font_path="simhei.ttf",
                          stopwords=load_stopwords(), mask=mask).generate(' '.join(words))
    plt.figure(figsize=(16, 9))
    plt.imshow(wordcloud, interpolation='bilinear')
    plt.axis('off')
    plt.show()


if __name__ == "__main__":
    titles = get_titles()
    words = process_titles(titles)
    generate_wordcloud(words)

第四章:真相大白

通过这一步,你不仅仅揭开了男朋友浏览记录中的关键词,还通过词云图清晰地看到了他最感兴趣的网站和内容。这些词云中,某些关键词异常突出,仿佛在告诉你他潜在的兴趣和关注点。

你笑了,关上电脑,轻松地靠在椅背上,心里已经没有了疑虑。男朋友的秘密已经在你掌控之中。🕵️‍♀️

相关推荐
用户99045017780095 分钟前
JeecgFlow之Camunda开发脚手架介绍,让天下没有难用的工作流
后端
敖行客 Allthinker5 分钟前
Go 语言中 panic 和 recover 的代价:性能与设计的权衡
开发语言·后端·golang
WenGyyyL8 分钟前
使用OpenCV和MediaPipe库——驼背检测(姿态监控)
人工智能·python·opencv·算法·计算机视觉·numpy
蹦蹦跳跳真可爱58921 分钟前
Python----数据分析(Matplotlib四:Figure的用法,创建Figure对象,常用的Figure对象的方法)
python·数据分析·matplotlib
小杨4041 小时前
python入门系列六(文件操作)
人工智能·python·pycharm
谦行1 小时前
前端视角 Java Web 入门手册 4.4:Web 开发基础—— Listener
java·后端
xiaozaq2 小时前
在Eclipse中安装Lombok插件
java·python·eclipse
云空2 小时前
《FastRTC:开启实时音视频应用开发新时代》
python·实时音视频
非优秀程序员2 小时前
使用Python给自己网站生成llms.txt
人工智能·后端·架构
尘鹄2 小时前
一文讲懂Go语言如何使用配置文件连接数据库
开发语言·数据库·后端·golang