本次的7个python爬虫小案例涉及到了re正则、xpath、beautiful soup、selenium等知识点,非常适合刚入门python爬虫的小伙伴参考学习。注:若涉及到版权或隐私问题,请及时联系我删除即可。(文末有福利)
1、使用正则表达式和文件操作爬取并保存“某吧”某帖子全部内容(该帖不少于5页。
本次选取的是某吧中的NBA吧中的一篇帖子,帖子标题是“克莱和哈登,谁历史地位更高”。爬取的目标是帖子里面的回复内容。
程序源代码:
import csv
import requests
import re
import time
def main(page):
url = f'https://tieba.baidu.com/p/7882177660?pn={
page}'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36'
}
resp = requests.get(url,headers=headers)
html = resp.text
# 评论内容
comments = re.findall('style="display:;"> (.*?)</div>',html)
# 评论用户
users = re.findall('class="p_author_name j_user_card" href=".*?" target="_blank">(.*?)</a>',html)
# 评论时间
comment_times = re.findall('楼</span><span class="tail-info">(.*?)</span><div',html)
for u,c,t in zip(users,comments,comment_times):
# 筛选数据,过滤掉异常数据
if 'img' in c or 'div' in c or len(u)>50:
continue
csvwriter.writerow((u,t,c))
print(u,t,c)
print(f'第{