半自动爬虫,顾名思义就是一半手动一半自动地进行爬虫,手动的部分是把网页的源代码复制下来,自动的部分是通过正则表达式把其中的有效信息提取出来。
在百度贴吧中任意寻找一个贴吧并打开一个热门帖子,将帖子的源代码复制下来,并保存为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文件中
结果:
扫描二维码关注公众号,回复:
14485197 查看本文章

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文件中
结果:
来源: