【发布时间】:2018-09-25 04:45:19
【问题描述】:
我正在尝试在 python 中使用 selenium 进行多处理。我的代码如下:
from selenium import webdriver
from multiprocessing import Pool
import xlwings as xw
driver = webdriver.Chrome('chromedriver.exe')
driver.get("https://example.com")
wb = xw.Book('my_file.xlsm')
sht = wb.sheets["Sheet1"]
final_list = []
search = driver.find_element_by_id("ContentPlaceHolder1_txtByName")
for item in search:
z = item.find_element_by_class_name("valuetext")
info = z.find_element_by_tag_name("span")
final_list.append(info.text)
def automate(num):
col = num
list_item = final_list[num]
sht.range(1, col).value = each
if __name__ == '__main__':
p = Pool(processes=4)
data = p.map(automate,range(1,20))
我遇到的问题是 4 个进程中的每一个都重新打开了网页,我不明白为什么。如果p.map 只针对automate 函数,那么为什么其余代码会针对每个进程运行?
我还是多处理的新手,所以不确定这是否就是它的工作原理。是否有另一种方法可以确保进程只针对函数本身,或者有什么方法可以使用线程?
【问题讨论】:
-
所有不在函数内的代码都会在你运行脚本时被执行。
-
另外,您不想与每个进程共享驱动程序的实例。我建议从支持并行性的框架开始,而不是自行开发。
标签: python multithreading selenium python-multiprocessing python-multithreading