Skip to main content
 首页 » 编程设计

python之尝试多处理时无法 pickle 本地对象

2025年01月19日13xing901022

我正在尝试对一个网站进行多处理抓取,在其中我获得了我想从中获取信息的所有节点的列表,然后生成一个池,因此它不是一个一个地获取数据,而是并行执行。我的代码如下:

from selenium import webdriver 
from selenium.webdriver.common.by import By 
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC 
import multiprocessing 
 
def ResPartido(node): 
 
   ft=node.find_element_by_css_selector('.status').text 
   if ft.strip()!='FT': return 
   hora=node.find_element_by_css_selector('.time').text 
   names=list() 
   for nam in node.find_elements_by_xpath( 
            './/td[contains(@style,"text-align")]/a[contains(@id,"team")]'): 
     name=nam.text 
     if '(N)' in name: 
        name=name.split('(N)')[0] 
     names.append(name) 
   score=node.find_element_by_css_selector('.red') 
 
   return [hora,name,score.text] 
 
if __name__ == "__main__": 
 
   browser=webdriver.Chrome() 
   SOME CODE 
   nodes=browser.find_elements_by_xpath( 
        '//tr[contains(@align,"center")]/following-sibling::tr[.//div[contains(@class,"toolimg")]]') 
   p = multiprocessing.Pool() 
 
   p.map(ResPartido,nodes)   <---Here is the error 
   ....... 
 
   >>AttributeError: Can't pickle local object '_createenviron.<locals>.encodekey' 

出现错误的我的 python 终端的图像

查看文档,它说列表是可选取的对象,在主要对象之前声明的函数也是如此,所以我不明白我在使用多处理时做错了什么。

请您参考如下方法:

根据我的阅读,问题是 nodes 是 webdriver 对象的列表,这些对象不可序列化。鉴于此,我唯一可以采用的方法如下。

1- 与其将整个标签作为节点列表的一个元素获取,不如仅获取使它与众不同的元素。在我的示例中,每一行都有一个序列号标识符

nodes=browser.find_elements_by_xpath( 
    '//tr[contains(@align,"center")]/following-sibling::tr[.//div[contains(@class,"toolimg")]]/@id').get_attribute() 
 
nodes=['1232489','1242356',......] 

2- 将其与浏览器一起传递给 map 功能

pr=partial(ResPartido,b=browser) 
p.map(pr,nodes) 

3- 在 ResPartido 函数中找到带有标识其@id 的字符串的唯一行

browser.find_elements_by_xpath('//tr[contains(@id,%s)]' %s node) 

有了这个我还没有测试过的绕过,我想我可以在没有 pickleable 对象问题的情况下得到我想要的东西