如果 CPU 和 RAM 已用尽,多处理和多线程的组合在 python 中是否有用?

Would the combination of Multiprocessing and Multithreading be useful in python if CPU and RAM are maxed out?

我已经了解多处理和多线程如何加速程序:

如果我正在执行的任务是 CPU 绑定和网络绑定怎么办?

我的项目是一个 selenium webscraper,它会循环遍历关键字列表以在亚马逊上进行搜索。搜索每个关键字后,我会提取第一页上所有产品的内容(标题、价格、评论、运输方式等)并将这些内容输出到一个 excel 文档中。

我在这个项目中遇到了一些主要障碍:

大部分 运行 时间似乎都花在了通过算法解析信息并上传到 excel 文档上。 请记住我的 CPU 和 RAM 使用已达到极限,多线程和多处理是否可以提高效率?

注意:我可以提供代码示例,但为了简单起见,我将其省略。我意识到简单的答案可能是:“上传到服务器”,但我想将其用作最后的手段。

WebDriver is not thread-safe. That being said, still you can serialise access to the underlying instance, you can share a reference in more than one thread. But this is not advisable. But you can always instantiate one WebDriver instance for each thread.

理想情况下,线程安全 问题不在您的代码中,而是在实际的浏览器绑定中。他们都假设一次只有一个命令,就像模拟真实用户一样。但另一方面,您始终可以为每个线程实例化一个 WebDriver 实例,这将启动多个浏览 tabs/windows。至此看来你的想法是完美的。

现在,不同的 threads 可以 运行 在同一个 Webdriver 上,但是测试的结果不会是你期望什么。背后的原因是,当你使用 or to run different tests on different tabs/windows a little bit of thread safety coding is required or else the actions you will perform like click() or send_keys() will go to the opened tab/window that is currently having the focus 而不管 thread 你期望是 运行ning。这基本上意味着所有测试将 运行 同时在具有 focusnot 的相同 tab/window 上 not =43=].

但是,一个可行的解决方案可能是使用 remote.webdriver,它是所有 Webdriver 子类型的 Abstract Base ClassAbstract Base Class 将允许注册 Webdriver 的自定义实现,以便 isinstance 类型检查成功。