爬虫---练习源码

选取的是网上对一些球员的评价,来评选谁更加伟大一点

复制代码
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'第{page}页爬取完毕')

if __name__ == '__main__':
    with open('01.csv','a',encoding='utf-8')as f:
        csvwriter = csv.writer(f)
        csvwriter.writerow(('评论用户','评论时间','评论内容'))
        for page in range(1,8):  # 爬取前7页的内容
            main(page)
            time.sleep(2)
相关推荐
沙漠之主9 小时前
Python 教学设计资料:从入门到实战的完整课程方案
爬虫·python
深蓝电商API17 小时前
用YOLO训练验证码目标检测模型的全流程
爬虫·yolo·目标检测·目标跟踪
wuyk5552 天前
Python网络爬虫入门到实战 第02章:HTTP/HTTPS协议超通俗精讲(GET/POST、请求头、响应码、爬虫核心基础)
爬虫·python·http
szial2 天前
网络爬虫与 CDP 实战(二):浏览器能访问,Python 却被拒绝?拆开登录态与 CSRF
爬虫·python·csrf
梅雅达编程笔记3 天前
04-Python CSV数据保存与翻页抓取
开发语言·爬虫·python·pandas·数据采集·csv
梅雅达编程笔记3 天前
03_网页表格数据抓取
爬虫·python·beautifulsoup·pandas·数据采集
傻啦嘿哟3 天前
爬虫代理IP池从0到1:构建高可用代理池,彻底解决IP被封问题
网络·爬虫·tcp/ip
szial3 天前
网络爬虫与 CDP 实战(一):网页数据到底在哪?从 HTTP 到分页采集
网络·爬虫·python·网络爬虫
深蓝电商API3 天前
反检测浏览器(比特/AdsPower)原理剖析与自建替代方案
爬虫·反检测浏览器
深蓝电商API4 天前
Puppeteer vs Playwright:多维度压测后的选型建议
爬虫·puppeteer·playwright