网站首页 > 技术文章 正文
1、需求背景:
在百度贴吧上选取一页帖子,点击右键查看源代码,将源代码保存为txt文件,通过python实现从该页面中抓取帖子的标题,作者,时间等信息,将结果保存为excel表格
2、关键技术实现:
python、正则表达式、txt文件读取、excel文件写入
3、代码实现:
import re
import csv
resultList = []
# 读取已经保存的文件内容
with open("baidutieba.txt", 'r', encoding="UTF-8") as f:
source = f.read()
#以下通过正则表达式进行相关的匹配,获取标题,作者,时间等信息
#原始文件是:<a rel="noopener" href="/p/7864139938" title="女高专一发展" target="_blank" class="j_th_tit ">女高专一发展</a>
titleRE = r'<a rel="noopener" href="/p/\d*" title="(.*?)" target='
titleList = re.findall(titleRE,source,re.S)
#原始文件是:title="主题作者: 五条永远滴神"
authorRE = 'title="主题作者: (.*?)"'
authorList = re.findall(authorRE,source,re.S)
#原始文件是:<span class="pull-right is_show_create_time" title="创建时间">18:48</span>
timeRE = '" title="创建时间">(.*?)</span>'
timeList = re.findall(timeRE,source,re.S)
#将如上的结果添加到列表里,便于后续写入到CSV格式的文档里
for i in range(len(titleList)):
result = {
"title": titleList[i],
"author": authorList[i],
"time": timeList[i]
}
resultList.append(result)
#将文件写入到excel表格里
with open('baidutieba.csv', 'w', encoding='utf-8-sig') as f:
writer = csv.DictWriter(f, fieldnames=['title','author','time'])
writer.writeheader()
writer.writerows(resultList)
4、运行代码,查看输出的 baidutieba.csv 文件,发现虽然能写入正确的内容,但是出现了换行。如下:
5、解决输出多加了空行的方法:
将源代码中:
with open('baidutieba.csv', 'w', encoding='utf-8-sig') as f:
修改为:
with open('baidutieba.csv', 'w', encoding='utf-8-sig', newline='') as f:
再次运行,出现的页面如图,空行问题已经解决:
猜你喜欢
- 2025-05-08 使用Python爬取给定网页的所有链接(附完整代码)
- 2025-05-08 python爬取电子课本,送给居家上课的孩子们
- 2025-05-08 Python爬虫实战,selenium模拟登录,Python实现抓取某东商品数据
- 2025-05-08 「2022 年」崔庆才 Python3 爬虫教程 - aiohttp 的基本使用
- 2025-05-08 Python爬虫实战:爬取动态网页数据
- 2025-05-08 python爬虫怎么副业接单(python爬虫在哪接单)
- 2025-05-08 「2022 年」崔庆才 Python3 爬虫教程 - 网页解析利器 XPath 初体验
- 2025-05-08 惊呆了!Python还能这样用?爬取网页数据并存储至本地数据库
- 2025-05-08 Python爬虫:如何实现异步加载爬取图片?
- 2025-05-08 使用ChatGPT编码抓取网页数据成功
- 263℃Python短文,Python中的嵌套条件语句(六)
- 262℃python笔记:for循环嵌套。end=""的作用,图形打印
- 261℃PythonNet:实现Python与.Net代码相互调用!
- 255℃Python操作Sqlserver数据库(多库同时异步执行:增删改查)
- 255℃Python实现字符串小写转大写并写入文件
- 113℃原来2025是完美的平方年,一起探索六种平方的算吧
- 94℃Python 和 JavaScript 终于联姻了!PythonMonkey 要火?
- 87℃Ollama v0.4.5-v0.4.7 更新集合:Ollama Python 库改进、新模型支持
- 最近发表
- 标签列表
-
- python中类 (31)
- python 迭代 (34)
- python 小写 (35)
- python怎么输出 (33)
- python 日志 (35)
- python语音 (31)
- python 工程师 (34)
- python3 安装 (31)
- python音乐 (31)
- 安卓 python (32)
- python 小游戏 (32)
- python 安卓 (31)
- python聚类 (34)
- python向量 (31)
- python大全 (31)
- python次方 (33)
- python桌面 (32)
- python总结 (34)
- python浏览器 (32)
- python 请求 (32)
- python 前端 (32)
- python验证码 (33)
- python 题目 (32)
- python 文件写 (33)
- python中的用法 (32)