【发布时间】:2020-07-20 09:32:52
【问题描述】:
我正在尝试实现以下目标。
- 使用 splinter 访问 URL
- 将浏览器实例传递给使用多进程 (multiprocessing.Process) 的所有方法
- 所有方法都在线程中执行,减少了总时间
示例代码如下所示。
from splinter import Browser
from multiprocessing import Process, Queue, current_process, freeze_support
#
# Function run by worker processes
#
def worker(input, output):
for func, args in iter(input.get, 'STOP'):
result = calculate(func, args)
output.put(result)
#
# Function used to calculate result
#
def calculate(func, args):
print(args)
result = func(*args)
return '%s says that %s%s = %s' % \
(current_process().name, func.__name__, args, result)
def get_meta_tag_title(browser):
return browser.find_by_xpath('//title')[0]['text']
def get_meta_tag_description(browser):
return browser.find_by_xpath('//description')[0]['text']
#
#
#
def test():
browser = Browser(headless=True)
browser.visit('https://example.com')
NUMBER_OF_PROCESSES = 2
TASKS1 = [(get_meta_tag_title, (browser)), (get_meta_tag_description, (browser))]
# Create queues
task_queue = Queue()
done_queue = Queue()
# Submit tasks
for task in TASKS1:
task_queue.put(task)
# Start worker processes
for i in range(NUMBER_OF_PROCESSES):
Process(target=worker, args=(task_queue, done_queue)).start()
# Get and print results
print('Unordered results:')
for i in range(len(TASKS1)):
print('\t', done_queue.get())
browser.quit()
if __name__ == '__main__':
freeze_support()
test()
我的问题是 -
- 这是正确的方法吗?,使用浏览器实例获取所有元素信息/值是否线程安全
- 将浏览器实例添加到队列会导致
TypeError: cannot serialize '_io.BufferedWriter' object我应该使用池吗?
【问题讨论】:
-
1.您在问题中说您正在使用线程,但您的代码正在使用进程。 2. 你真的有性能问题吗?瓶颈是什么?
-
是的,基本上我的代码使用浏览器实例来查找元标记、内联样式、内部链接、社交链接等一些东西。我想让这些功能同时运行以减少整体执行时间。
标签: python multithreading thread-safety python-multithreading splinter