团队冲刺阶段二(6)

  爬取到了帖子的标题,还要对帖子的评论进行爬取,这其中就会有更多的服务器访问,因此出现反爬虫设定的概率就更大了,因此决定控制过一段时间进行一次爬虫,每个帖子不要爬取过多的内容,以此来保证可以让数据库不会太缺少内容。

应对爬虫出现问题的方法,因为解决不了验证,只能每次爬取少量内容,给程序设置了一个定时器,每经过20分钟运行以此,以此来防止验证出现频繁。

代码如下:

import pymysql
import requests
import re
import time
db = pymysql.connect(host="localhost", user="root", passwd="", database="tbpy", charset='utf8mb4')
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36(KHTML, like Gecko) Chrome/83.0.4103.106 Safari/537.36"
}
cursor = db.cursor()
sql = 'select id from total order by looknum desc limit 115,99999999'
cursor.execute(sql)
results = cursor.fetchall() #用于返回多条数据
print(results)

def getpinglun(resul):
user = []
totalll=115
numm=0
for w in resul:
pUrl = "https://tieba.baidu.com"+w[0]
# print(pUrl)
res2 = requests.get(pUrl).text
# getP = re.compile(r'<a style="" target="_blank" class="p_author_face " href="(.*?)"><img username=".*?" class="" src="(.*?)"/></a>')
getT = re.compile(r'<a style="" target="_blank" class="p_author_face " href="(.*?)"><img username=".*?" class="".*?"(//himg.bdimg.com/sys/portrait/item/.*?)".*?/></a>.*?class="p_author_name j_user_card" href=".*?" target="_blank">(.*?)<.*?class="d_post_content j_d_post_content clearfix" style="display:;"> (.*?)<', re.DOTALL)
getPage = re.compile(r'<span class="red">(.*?)</span>页')
keyPage = re.findall(getPage, res2)
# keyP = re.findall(getP, res2)
# user.append([keyP[0][0], keyP[0][1]])
page = keyPage[0]
if(int(page)>5):
page=5
else :
page=page
print(int(page))
for a in range(int(page)):
pageUrl = pUrl+"?pn="+str(a+1)
print(pageUrl)
res3 = requests.get(pageUrl).text.replace("<br>", "")
keyT = re.findall(getT, res3)
print(keyT) # 评论人名 链接 头像 评论 0=链接 1=头像 2=昵称 3=评论
user.append(keyT)
for info in keyT:
va = []
va.append(w[0])
va.append(info[2])
va.append(info[0])
va.append(info[1])
va.append(info[3])
sql1="insert into plinfo (id,plname,peohref,peoimg,plneirong) values(%s,%s,%s,%s,%s) "
cursor.execute(sql1, va)
db.commit()
totalll=totalll+1
jieguo="已经爬取完了第"+str(totalll)+"条数据"
print(jieguo)
numm=numm+1
if(numm==5):
time.sleep(1800)
numm=0
if __name__ == '__main__':
getpinglun(results)
posted @   软工新人  阅读(31)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示