爬虫常用模板

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

爬虫工具库-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()
相关推荐
孙启超1 小时前
【AI开发之Rust】第 7 课:错误处理 —— panic、Result 与 `?`
人工智能·分布式·后端·爬虫·spring cloud·架构·rust
该逃避避10 小时前
IP代理类型介绍:住宅IP、机房IP、移动IP等区别与选择
爬虫
科技苑19 小时前
Python简单网络爬虫教程
爬虫·python
szephyr1 天前
Python 爬虫合规与反爬实战:从 requests 到 Playwright
爬虫·python·requests·playwright·反爬
深蓝电商API1 天前
MCP 与 AI Agent 如何改变爬虫开发模式?
爬虫·agent·mcp
小花皮猪1 天前
2026 代理网络选型指南:住宅/机房/ISP/移动代理怎么选?(附 Bright Data / Oxylabs / Decodo 实测对比)
爬虫·数据采集·代理
数据狐(Datafox)1 天前
1688商品列表API接口解析(附 JSON 样例)
java·开发语言·数据库·爬虫·json
深蓝电商API1 天前
大语言模型能否自动完成 JS 逆向?
爬虫·js逆向
不叫猫先生1 天前
2026 Web Scraping 代理服务商怎么选?住宅代理与代理网络对比指南
爬虫·网络代理·代理·住宅代理
SEO_juper2 天前
Java 并发编程实战:从线程基础到高并发架构
运维·人工智能·爬虫·chatgpt·seo