当前位置:网站首页>半自动爬虫
半自动爬虫
2022-08-09 13:58:00 【东方不败就是我】
半自动爬虫,顾名思义就是一半手动一半自动地进行爬虫,手动的部分是把网页的源代码复制下来,自动的部分是通过正则表达式把其中的有效信息提取出来。
在百度贴吧中任意寻找一个贴吧并打开一个热门帖子,将帖子的源代码复制下来,并保存为source.txt。Python读入这个source.txt文件,通过正则表达式获取用户名、发帖内容和发帖时间,并保存为result.csv。涉及的知识点如下。
(1)在浏览器中查看网站的源代码。 网页右键/可以辅助F12元素查找。
(2)使用Python读文本文件。
(3)正则表达式的应用。
(4)先抓大再抓小的匹配技巧。 (先把每一块取出来,再在这些块里匹配规则)
(5)使用Python写CSV文件。
1、直接读取。
缺点:用户名和内容可能不匹配。
import re
import csv
with open('text.txt',encoding='utf-8') as f:
content=f.read()
# every_reply=re.findall('class="l_post l_post_bright j_l_post clearfix "(.*?)p_props_tail props_appraise_wrap', content,re.S)
result_list=[]
username_list = re.findall('username="(.*?)"', content,re.S)
content_list= re.findall('j_d_post_content " style="display:;">(.*?)<', content,re.S)
reply_time_list=re.findall('"tail-info">(.*?)<', content,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)
import csv
with open('result.csv','w',encoding='utf-8')as f:
write=csv.DictWriter(f,fieldnames=['username','content','reply_time'])#写入CSV文件的列名行:
write.writeheader()
write.writerows(result_list)#将包含字典的列表全部写入到CSV文件中
结果:

2、先按块读取,再从每块中读取。
import re
import csv
with open('text.txt',encoding='utf-8') as f:
content=f.read()
result_list=[]
every_reply=re.findall('class="l_post l_post_bright j_l_post clearfix "(.*?)p_props_tail props_appraise_wrap', content,re.S)
for each in every_reply:
result={}
result['username']=re.findall('username="(.*?)"', each,re.S)[0]
result['content']=re.findall('j_d_post_content " style="display:;">(.*?)<', each,re.S)[0]
result['reply_time']=re.findall('"tail-info">(20.*?)<', each,re.S)[0]
result_list.append(result)
import csv
with open('result2.csv','w',encoding='utf-8')as f:
write=csv.DictWriter(f,fieldnames=['username','content','reply_time'])#写入CSV文件的列名行:
write.writeheader()
write.writerows(result_list)#将包含字典的列表全部写入到CSV文件中
结果:
来源:

边栏推荐
- *3-3牛客网 重新排列
- Assembly language learning (5)
- YOLOv5网络详解
- Small program template production process, small program template production is convenient and fast
- [MRCTF2020]套娃-1
- C语言,if循环 for 循环 while循环 switch循环 do...while()循环
- #25-1 OJ 78 Calculate birthday day of the week
- RHCE课程总结
- *3-4 CCF 2014-09-3 String matching
- Shell course summary
猜你喜欢
随机推荐
word编号和文本间距过大
vivo手机上的系统级消息推送平台的架构设计实践
使用 compose 的 Canvas 自定义绘制实现 LCD 显示数字效果
RHCE Course Summary
Shell course summary
Minesweeper game
apt-cache 命令
*2-4 每日温度 *2-5 接雨水
RHCE课程总结
【视频编码学习】——SAD和SATD
[manjaro]更新后内核文件加载失败
青蛙跳台阶
Assembly language learning (2)
IK学习笔记(1)——CCD IK
*1-2 OJ 190 run-length code
*5-2 CCF 2014-12-3 集合竞价
三子棋的代码实现
*5-1 CCF 2015-03-1 图像旋转
* 2-2 OJ 1163 missile interception of beta
除了开心麻花,中国喜剧还有什么?








