我正在尝试编写我的第一个Python脚本,并且使用了大量的Google搜索,我认为我已经完成了.但是,我需要一些帮助才能让自己走完终点.
我需要编写一个脚本,登录到启用cookie的站点,刮掉一堆链接,然后生成一些进程来下载文件.我有程序在单线程中运行,所以我知道代码工作.但是,当我试图创建一个下载工作池时,我碰到了一堵墙.
#manager.py
import Fetch # the module name where worker lives
from multiprocessing import pool
def FetchReports(links,Username,Password,VendorID):
pool = multiprocessing.Pool(processes=4, initializer=Fetch._ProcessStart, initargs=(SiteBase,DataPath,Username,Password,VendorID,))
pool.map(Fetch.DownloadJob,links)
pool.close()
pool.join()
#worker.py
import mechanize
import atexit
def _ProcessStart(_SiteBase,_DataPath,User,Password,VendorID):
Login(User,Password)
global SiteBase
SiteBase = _SiteBase
global DataPath
DataPath = _DataPath
atexit.register(Logout)
def DownloadJob(link):
mechanize.urlretrieve(mechanize.urljoin(SiteBase, link),filename=DataPath+'\\'+filename,data=data)
return True
Run Code Online (Sandbox Code Playgroud)
在此修订版中,代码失败,因为cookie尚未传输给工作者以供urlretrieve使用.没问题,我能够用机械化的.cookiejar类保存cookies在经理,并传递给工人.
#worker.py
import mechanize
import atexit
from multiprocessing import current_process
def _ProcessStart(_SiteBase,_DataPath,User,Password,VendorID):
global cookies
cookies = mechanize.LWPCookieJar()
opener = mechanize.build_opener(mechanize.HTTPCookieProcessor(cookies))
Login(User,Password,opener) # note I pass the opener to Login …Run Code Online (Sandbox Code Playgroud)