【问题标题】:Selenium and asyncio硒和异步
【发布时间】:2018-02-20 23:28:01
【问题描述】:

完成这项工作的最佳方法是什么? 由于 Selenium 不能很好地与 asyncio 配合使用,因此机器人最终会死掉。 它按预期工作,但最终会崩溃。我确实明白问题出在哪里,尤其是硒太重了,但是有什么好的解决方法吗?

我收到错误消息: 任务已销毁,但处于待处理状态!

我没有其他任何东西,没有追溯。 我必须重新启动机器人(不和谐),它会再次工作一段时间。

@bot.command(pass_context=True)
async def weather(ctx, arg):
    if ctx:
        list = ('lf','oahu')
        await bot.say('*Loading webdriver.....*')
        if arg in list:
            if arg == 'lf':
                website = '--'
                name = 'Los Feliz Map'
            if arg == 'oahu':
                website = '--'
                name = 'Oahu Map'
            load_site = webdriver.Chrome()
            # load site on chrome
            load_site.get(website)
            await bot.say('*Loading ' + str(name) + '...*')
            load_site.find_element_by_xpath('//*[@id="main-map"]/div[2]/div[1]/div/a[2]').click()
            load_site.find_element_by_xpath('//*[@id="main-map"]/div[2]/div[2]').click()
            load_site.find_element_by_xpath('//*[@id="main-map"]/div[2]/div[2]/div/form/div[3]/label[6]/div/span').click()
            await asyncio.sleep(2) #sleep to ensure weather loads on site before screenshot
            load_site.save_screenshot('weather.png')
            await bot.say('*Taking screenshot and saving image....*')
            await bot.send_file(ctx.message.channel, 'weather.png')
            load_site.quit()
            print('Succesfully sent image of ' + str(arg) + ' - ' + str(ctx.message.author.name))

我忽略了该网站,因为它是一个私人网站。

【问题讨论】:

  • 我认为你不会有太大的成功。像 selenium 这样的阻塞 API 在异步应用程序中确实不起作用。您最好的选择是使用专门构建的异步库。 arsenic 似乎大致如此,但您必须尝试一下。
  • 是的,我发现了砒霜,肯定需要阅读一下。幸运的是,“单击”和“屏幕截图”仍然适用于砷,但乍一看,我没有看到任何关于使用 xpath 搜索的内容。今晚晚些时候再看,谢谢。
  • 你可以使用run_in_executor在它自己的线程中运行阻塞代码而不阻塞。然后,您可以在线程中运行所有代码并返回所需的内容。请参阅此处的示例:stackoverflow.com/questions/53587063/…
  • 你可以试试playwright,它支持异步使用。
  • 使用浏览器是个坏主意(一般来说),你最好使用 aiohttp 和漂亮的汤来抓取网站

标签: python-3.x selenium-webdriver python-asyncio discord.py


【解决方案1】:

简短的回答:这是不可能的。如果你设法让它工作,它就不会很好地工作。

长答案:Selenium 是一个阻塞 API,你不能真正将它与异步脚本一起使用。如果您真的想使用网络浏览器,您可以尝试找到类似 https://pypi.org/project/aioselenium/ 的替代方案。

【讨论】:

    【解决方案2】:

    您可以在使用 discord.py 的同时使用 aiohttp 向 API 发出请求

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      • 2010-11-27
      • 2013-06-12
      • 1970-01-01
      • 2018-03-01
      • 1970-01-01
      • 2012-10-14
      相关资源
      最近更新 更多