爬虫笔记 – 关于Pyppeteer的使用

前言:

pyppeteer 比 selenium 在安装方面又更好的优势,第一次使用会自动下chromium
而且pyppeteer 的语法比selenium 略微简洁,这也是我选择pyppeteer的原因
但是貌似chromium在Centos下缺少若干运行库,以下是我的history过程:
   89  repoquery --nvr --whatprovides libappindicator3.so.1
   90  yum repoquery --nvr --whatprovides libappindicator3.so.1
   91  yum install -y libappindicator-gtk3-12.10.0-19.el8
   92  python main.py
   93  yum repoquery --nvr --whatprovides libnss3.so
   94  yum install -y nss-3.53.1-17.el8_3
   95  python main.py
   96  yum repoquery --nvr --whatprovides libXss.so.1
   97  yum install -y libXScrnSaver-1.2.3-1.el8
   98  python main.py
   99  yum repoquery --nvr --whatprovides libasound.so.2
  100  yum install -y alsa-lib-1.2.4-5.el8
repoquery --nvr --whatprovides XXX  ## 查询谁提供了XXX的依赖包

yum install -y YYY 安装这个YYY

我依靠以上两个命令手动下载了chromium的所有依赖包,然后成功使用上了Centos的chromium

使用:

Pyppeteer在网上的教程少之又少,这是我自己整理的一些东西:

首先在运行之前我们需要定义一个异步:

async def main():
    ---代码内容
asyncio.get_event_loop().run_until_complete(main())

所以我们还要安装asyncio

pip install asyncio

首先初始化一个浏览器,直接复制就行了:

browser = await pyppeteer.launch(
        headless=True,  #如果是True,那就chromium后台启动(如果要调试就改成False)
        args=[
            "--disable-dev-shm-usage", #没打备注都是一些优化,否则卡的要死
            "--disable-extensions",
            "--hide-scrollbars",
            "--disable-bundled-ppapi-flash",
            "--mute-audio",
            "--no-sandbox", #必须禁止沙盒模式,否则无法在centos打开chromium
            "--disable-setuid-sandbox",
            "--disable-gpu",
            "–-single-process",
            "--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36" #UA可带可不带
        ],
        dumpio=True, #解决chromium浏多开页面卡死问题
    )

打开浏览器并且打开网页:

page = await browser.newPage() #新建一个浏览器界面
            await page.setRequestInterception(True) #以下是过滤掉图片/字体/CSS 防止打开过卡,根据你需要的资源自己定义
            async def intercept(request):
                if any(request.resourceType == _ for _ in ("image", "eventsource", "websocket", "stylesheet", "font")):  #"image", "media", "eventsource", "websocket", "stylesheet", "font"
                    await request.abort()
                else:
                    await request.continue_()
            page.on('request', lambda req: asyncio.ensure_future(intercept(req))) #到这里为止
            await page.goto(url) #打开一个网站界面
            page_text = await page.content()  # 获取页面内容
            await page.close() #关闭界面

其他的东西:

await browser.close() #关闭浏览器,最后退出的时候你需要这个

await page.waitFor(3 * 1000) #等待3秒后运行

 

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容