day5、365yg视频抓取-

365yg视频抓取--def方法
得到网址,但这个视频接口无法用普通方法下载,现存入本地,若以后有可下载软件,即可使用

import requests
from lxml import etree
import json
from selenium import webdriver
from time import sleep

#爬取365yg的视频
#相关网址"http://www.365yg.com/"


#定义一个函数处理json数据
def handle_json(json_url, page):
    headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}
    r = requests.get(url=json_url%page, headers=headers)
    #对json数据进行解析,生成obj类型
    obj = json.loads(r.text)
    return obj["data"]


#定义一个函数,用于处理json数据
def handle_video(video_list):
    for video in video_list:
        #获取vedio_id作为键
        video_id = video["video_id"]
        source_url = "http://365yg.com" + video["source_url"]
        download_video(source_url, video_id)


def download_video(video_url, video_id):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36'}
    # v_data = requests.get(url=video_url, headers=headers)
    # with open("video.html", "wb") as fp:
    #     fp.write(v_data.content)
    #通过页面下载发现该页面是动态加载
    driver = webdriver.Chrome()#PhantomJS不支持此页面可能版本太旧,作者已不更新PhantomJS
    driver.get(video_url)
    sleep(3)

    #用xpath选取video的url
    html_tree = etree.HTML(driver.page_source)
    video_src = html_tree.xpath("//video/@src")[0]
    # print(video_src)
    sleep(3)
    driver.quit()
    #得到网址,但这个视频接口无法用普通方法下载,现存入本地,若以后有可下载软件,即可使用
    res = requests.get(video_src, headers=headers)
    # with open("video1.html", "w") as fp:
    #     fp.write(res)

def main():
    start = int(input("请输入起始页:"))
    end = int(input("请输入终止页:"))
    json_url = "https://365yg.com/api/pc/feed/?category=video&utm_source=toutiao&widen=%d&max_behot_time=0&max_behot_time_tmp=0&tadrequire=true&as=A1253AF48A0FCE5&cp=5A4A4F4CAEE59E1&_signature="
    # 定义一个列表变量,用于整合所有的json数据
    video_list = []
    for i in range(int(start), int(end)+1):
        json_list = handle_json(json_url, i)
        video_list += json_list
    return video_list

if __name__ == "__main__":
    main()

你可能感兴趣的:(day5、365yg视频抓取-)