半自动化爬虫-爬取一个网站的内容及回复

  • 需求:爬取某个帖子的内容以及回复。
  • 步骤:
  1. 首先到该页面存储好该页面的源代码。右击该页面,选择【查看该页面源代码】,将得到的页面中的文本全部复制到一个文本文档中。
  2. 将文件存储好之后,修改好需要得到的一些值的正则表达式,将文件路径改好,运行以下代码。
    注意:正则表达式一定要根据需要获取数据的需要来进行编写。多个空格可以使用\\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)
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值