当前位置:网站首页>半自动爬虫
半自动爬虫
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文件中
结果:
来源:

边栏推荐
猜你喜欢
随机推荐
*5-2 CCF 2014-12-3 集合竞价
*1-3 OJ 291 The mouse and cat trade
测试研发的人数科学比例
*3-4 CCF 2014-09-3 String matching
[Video coding learning] - SAD and SATD
RHCE课程总结
*4-1 CCF 2014-12-1 Access Control System
同事的接口文档我每次看着就头大,毛病是真的多多多。。。
零时科技 | Nomad 跨链桥被盗1.8亿美元事件分析
word编号和文本间距过大
RHCE课程总结
Recursive implementation of the Tower of Hanoi problem
ELK部署
汇编语言学习(二)
深圳堡垒机厂家有哪些?重点推荐哪家?
Assembly language learning (2)
汇编语言学习(九)
*1-1 OJ 56 Hamming Distance
*3-2 CCF 2014-09-2 drawing
*1-4 OJ 605 Gray Code








