Administrator
发布于 2022-09-28 / 490 阅读
0
0

爬取腾讯视频

#coding:utf-8
# 导库
import requests
import json
import time
import pandas as pd
# 用pandas这么个库,为了保存csv格式
df = pd.DataFrame()

# 循环语句
# for xxx in range(a,b,c):
# for a in range(1,4):
#     print(a)

dataArray = [] 
# 可遍历的对象
for page in range(2, 3):
    # headers 伪造身份 
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'}
    
    #### 构造url ####
    # https:协议头
    # mfm.video.qq.com : URL
    # ? 后面是参数名,可以有多个,用&来分割
    # otype 类型  otype = json×tamp={}    
    # target_id 视频ID 
    # count 返回的弹幕数量
    ####### {} 在python里面,叫做占位符
    url = 'https://mfm.video.qq.com/danmu?otype=json×tamp={}&target_id=5938032297%26vid%3Dx0034hxucmw&count=20'.format(page)
    # 发起一个http的Get请求,相当于 在浏览器的地址栏输入url后,敲下回车键
    # 然后把response用html这个变量存储
    html = requests.get(url,headers = headers)
    # <代表对象>
    # Response是对象的类型 200 是HTTP的状态码 404:not found
    # <Response [200]>
    # print(html.text)

    # 将string转化为json,格式化
    bs = json.loads(html.text,strict = False)  #strict参数解决部分内容json格式解析报错
    # json操作,用key来获取value
    
    # bs['comments'] 是个 Array,可以遍历
    # 休息一秒钟,目的是防止反爬虫机制    
    # #遍历获取目标字段
    # for i in bs['comments']:
    #     content = i['content']  #弹幕
    #     upcount = i['upcount']  #点赞数
    #     user_degree =i['uservip_degree'] #会员等级
    #     timepoint = i['timepoint']  #发布时间
    #     comment_id = i['commentid']  #弹幕id
    dataArray += bs['comments']
    time.sleep(1)
# 怎么把一个json 转成csv去存储
# 语法糖,简化文件操作的
# 第一个参数是文件名: temp.json
# 第二个参数是文件mode:w: write , r
# 文件的引用类型


with open("temp.csv",'w',encoding="utf-8") as f:
    # 写内容,写什么内容,写到哪
    # unicode
    # 第一步,写列名 \n是换行
    outputStr = ",弹幕,点赞数\n"
    for singleLine in dataArray:
        # 拼接字符串
        singleLineStr = "0,{},{}\n".format(singleLine['content'],singleLine['upcount'])
        outputStr = outputStr + singleLineStr

    f.write(str(outputStr))

    # json.dump(dataArray,f,ensure_ascii=False)
    

评论