半自动化爬虫
- 需求:爬取某个帖子的内容以及回复。
- 步骤:
注意:正则表达式一定要根据需要获取数据的需要来进行编写。多个空格可以使用\s+来匹配。
import re import csv with open('./data/半自动化爬虫-抗压背锅吧.txt','r',encoding='utf-8') as f: source=f.read()
result_list=[] username_list=re.findall('username="(.*?)"',source,re.S) content_list=re.findall('class="d_post_content j_d_post_content " style="display:;">\s+(.*?)<',source, re.S) reply_time_list=re.findall('class="tail-info">(2022.*?)<',source, re.S)
for i in range(len(username_list)): result={'username': username_list[i], 'content': content_list[i], 'reply_time': reply_time_list[i]} result_list.append(result) with open('半自动化爬虫-抗压背锅吧.csv','w',encoding='utf-8') as f: writer=csv.DictWriter(f,fieldnames=['username','content','reply_time']) writer.writeheader() writer.writerows(result_list)
- 最终得到的结果是一个表格,由于有些部分是图片,所以提取不出来,这里只能提取出文字部分。
- 修改后的代码
import re import csv with open('./data/半自动化爬虫-抗压背锅吧.txt','r',encoding='utf-8') as f: source=f.read()
# 获得包含每一层所有信息的大块文本 every_reply=re.findall('class="l_post l_post_bright j_l_post clearfix "(.*?)p_props_tail props_appraise_wrap',source, re.S)
# 从每一个大文本快里面提取出各个楼层的发帖人姓名,发帖时间和发帖内容 for each in every_reply: result={} result['username'] = re.findall('username="(.*?)"',source,re.S)[0] result['content'] = re.findall('class="d_post_content j_d_post_content " style="display:;">\s+(.*?)<',source, re.S) result['reply_time'] = re.findall('class="tail-info">(2022.*?)<',source, re.S)
with open('半自动化爬虫-抗压背锅吧1.csv','w',encoding='utf-8') as f: writer=csv.DictWriter(f,fieldnames=['username','content','reply_time']) writer.writeheader() writer.writerows(result_list)
相关文章
- 谷歌地图之类的api要在 maui 里面使用, 需要授权0.0.0.0的IP
- 萝卜爆肝Python爬虫学习路线
- 词云绘制,推荐三种 Python包外加一个在线网站!
- [源码解析] PyTorch分布式优化器(3)---- 模型并行
- X-Gorgon算法参数获取(python版,附源码)
- 面试突击87:说一下 Spring 事务传播机制?
- 100道Python练习题,看看你能会几题!?
- Python地图绘制工具folium更换地图底图样式全攻略
- 【爬虫+可视化】Python爬取疫情数据,并做可视化展示
- 面试突击80:说一下 Spring 中 Bean 的生命周期?
- 面试突击45:为什么要用读写锁?它有什么优点?
- 面试突击43:lock、tryLock、lockInterruptibly有什么区别?
- synchronized有几种用法?
- try-catch-finally中的4个大坑,不小心就栽进去了!
- 作为程序员的基本素养,你了解Python变量引用吗
- 查找数组中最大值的5种方法!(动图演示)
- pyspark on hpc
- 一点思考|工作十几年了,竟从未用过do-while!
- 定时任务最简单的3种实现方法(超实用)
- 啪啪,打脸了!领导说:try-catch必须放在循环体外!