脚本运行前提需要安装chrome浏览器并配置好chrome driver,常规爬虫无法爬取到快手视频信息,只能使用该方式。 首先脚本会打开快手首页,需要在30s内完成登录。 然后程序会自动打开视频播放网页,暂停视频,并开始下载,完成后自动播放下一个视频。 使用时可以根据需要的视频数量做一个循环,或者当下载的视频开始重复时就结束了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| import time from selenium import webdriver from lxml import etree import wget
def get_source(url): options = webdriver.ChromeOptions() options.add_experimental_option("excludeSwitches", ['enable-automation', 'enable-logging']) driver_path = r"C:\Users\王殊勋\AppData\Local\Google\Chrome\Application\chromedriver.exe" browser = webdriver.Chrome(executable_path=driver_path, options=options) browser.get('https://www.kuaishou.com') #打开快手进行登录 time.sleep(30) browser.get(url) time.sleep(5) click=browser.find_element_by_xpath("/html/body/div/div[1]/section/div/div/div/div[1]/div[2]/div[1]/div[2]/div/div[1]") click.click() #暂停视频,避免出现视频播放完毕,下载还未完成。 while True: html=browser.page_source html2 = etree.HTML(html) url = html2.xpath('/html/body/div/div[1]/section/div/div/div/div[1]/div[2]/div[1]/div[2]/video/@src') #匹配视频地址 wget.download(url[0], out='video.mp4') #下载地址和文件名 click=browser.find_element_by_xpath("/html/body/div/div[1]/section/div/div/div/div[1]/div[2]/div[2]/div[2]") click.click() #点击下一个视频 time.sleep(10) click=browser.find_element_by_xpath("/html/body/div/div[1]/section/div/div/div/div[1]/div[2]/div[1]/div[2]/div/div[1]") click.click() #暂停视频,避免出现视频播放完毕,下载还未完成。 if __name__ == '__main__': lista=[] get_source('https://www.kuaishou.com/short-video/3xh4isefmx7bhke?authorId=3x3tcmceva9zu3s&streamSource=profile¤tPcursor=1.611224410671E12&area=profilexxnull') #视频网页地址
|
该脚本在python3.9验证通过。