爬虫常用模板

这里记录的是我学习爬虫自己用到的一些东西,方便以后打开直接使用。我会不定期的往里面添加内容。

爬虫工具库-spidertools.cn

协程

模板1(通过loop):

python 复制代码
async def download()
    pass


async def main():
    # 创建任务队列
    tasks = []

    for..........{     
        # 使用for循环调用其它异步函数,添加到任务队列中
        asks.append(asyncio.create_task(download()))
    }

    # 打包提交队列
    await asyncio.gather(*tasks)


if __name__ == '__main__':
    # 创建loop
    loop = asyncio.get_event_loop()

    # 通过loop执行异步函数
    loop.run_until_complete(main())

模板2(通过asyncio):

python 复制代码
async def download()
    pass


async def main():
    # 创建任务队列
    tasks = []

    for..........{     
        # 使用for循环调用其它异步函数,添加到任务队列中
        asks.append(asyncio.create_task(download()))
    }

    # 等待任务结束
    await asyncio.wait(tasks)


if __name__ == '__main__':
    asyncio.run(main()) 

python运行js模板

python 复制代码
import execjs


# 打开本地js文件,读取文件内容后通过execjs.compile函数将其转换成js代码暂存在ctx中
with open('baidu.js', 'r', encoding='utf-8') as f:
    ctx = execjs.compile(f.read())


# 使用 ctx.call 函数来调用JS代码中的函数
# 第一个参数:想要调用的js中的函数
# 第二个参数:传入的值
res = ctx.call('hello', lis)

ffmpeg视频合成

在爬取视频的时候通常是通过m3u8来获取到视频的ts切片,需要把他们全部合成为一个视频切片。

复制代码
def concat():
    video = 'output.mp4'    # 视频输出地址
    ts_locat = './视频切片'      # ts文件路径 

    # 获取所有的 .ts 文件
    ts_files = [f for f in os.listdir(ts_locat) if f.endswith('.ts')]
    ts_files.sort()  # 排序以确保正确的顺序

    # 将排序好的ts文件目录按行依次写入到一个txt文本中
    with open('concat_list.txt', 'w', encoding='utf-8') as f:
        for ts_file in ts_files:
            f.write(f"file '{ts_locat+ '/' +ts_file}'\n")

    # 使用 ffmpeg 读取文本中的ts文件目录地址,按顺序拼接所有的 .ts 文件
    ffmpeg.input('concat_list.txt', format='concat', safe=0).output(video, c='copy').run()
相关推荐
深蓝电商API2 小时前
异步爬虫防封策略:随机User-Agent与延时
爬虫·python
深蓝电商API2 小时前
asyncio+playwright实现超高性能异步爬虫
爬虫·python
冰敷逆向2 小时前
京东h5st纯算分析
java·前端·javascript·爬虫·安全·web
小白学大数据3 小时前
Python爬虫实现无限滚动页面的自动点击与内容抓取
开发语言·爬虫·python·pandas
0思必得03 小时前
[Web自动化] Selenium处理Cookie
前端·爬虫·python·selenium·自动化
喵手3 小时前
Python爬虫实战:房价/租金指数时间序列爬虫实战 - 从多页采集到趋势分析的完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·房价/租金指数时间序列·多页采集到趋势分析·采集结果sqlite到处
B2_Proxy4 小时前
如何使用代理服务解决“您的 ASN 被阻止”错误:全面策略分析
网络·爬虫·网络协议·tcp/ip·安全·代理模式
EdgeOne边缘安全加速平台4 小时前
一键管控 AI 爬虫,腾讯 EdgeOne 基础 Bot 管理能力免费开放
人工智能·爬虫
喵手5 小时前
Python爬虫实战:房产数据采集实战 - 链家二手房&安居客租房多页爬虫完整方案(附CSV导出 + SQLite持久化存储)!
爬虫·python·爬虫实战·零基础python爬虫教学·房产数据采集·链家二手房/安居客房源采集·采集结果sqlite导出
咩咩不吃草6 小时前
【HTML】核心标签与【Python爬虫库】实战指南
css·爬虫·python·html