如何使用selenium的多个实例[python]

Lui*_*uez 2 python selenium web-scraping

我正在使用 selenium 进行网络抓取,但它太慢了,所以我尝试使用 to 实例来加快速度。

我想要完成的是:

1) 创建instance_1
2) 创建instance_2
3) 在第一个实例中打开一个页面,
不执行任何操作
4) 在第一个实例中打开一个页面,
保存第一个实例的内容
5) 在第一个实例中打开一个新页面,
保存第一个实例的内容第二审

这个想法是利用加载第一个页面所需的时间来打开第二个页面。

links = ('https:my_page'+ '&LIC=' + code.split('_')[1] for code in data)

browser = webdriver.Firefox()
browser_2 = webdriver.Firefox()


first_link = links.next()
browser.get(first_link)
time.sleep(0.5)

for i,link in enumerate(links): 

        if i % 2:       # i starts at 0
            browser_2.get(link)
            time.sleep(0.5)
            try: 
                content = browser.page_source
                name = re.findall(re.findall('&LIC=(.+)&SAW',link)[0]
                with open(output_path  + name,'w') as output:
                    output.write((content_2))

                print 'error ' + str(i) 

        else:

            browser.get(link)
            time.sleep(0.5)
            try:
                content_2 = browser_2.page_source
                name = re.findall(re.findall('&LIC=(.+)&SAW',link)[0]
                with open(output_path  + name,'w') as output:
                    output.write((content ))

            except:
                print 'error ' + str(i) 
Run Code Online (Sandbox Code Playgroud)

但脚本会等待第一个页面完全充电后再打开下一个页面,而且这种方法仅限于同时打开页面

编辑。

我对 GIRISH RAMNANI 的代码做了以下更改

在函数外部创建浏览器实例

driver_1 = webdriver.Firefox()
driver_2 = webdriver.Firefox()
driver_3 = webdriver.Firefox()

drivers_instance = [driver_1,driver_2,driver_3]
Run Code Online (Sandbox Code Playgroud)

使用驱动程序和 url 作为函数的输入

 def get_content(url,driver):    
    driver.get(url)
    tag = driver.find_element_by_tag_name("a")
    # do your work here and return the result
    return tag.get_attribute("href")
Run Code Online (Sandbox Code Playgroud)

使用 zip 函数创建一对链接/浏览器

with ThreadPoolExecutor(max_workers=2) as ex:
    zip_list = zip(links, cycle(drivers_instance)) if len(links) > len(drivers_instance) else zip(cycle(links), drivers_instance)
    for par in zip_list:

       futures.append(ex.submit(get_content,par[0],par[1]))
Run Code Online (Sandbox Code Playgroud)

GIR*_*ANI 8

concurrent.futures可以在这里使用。

from selenium import webdriver
from concurrent.futures import ThreadPoolExecutor

URL ="https://pypi.python.org/pypi/{}"

li =["pywp/1.3","augploy/0.3.5"]

def get_content(url):    
    driver = webdriver.Firefox()
    driver.get(url)
    tag = driver.find_element_by_tag_name("a")
    # do your work here and return the result
    return tag.get_attribute("href")


li = list(map(lambda link: URL.format(link), li ))


futures = []
with ThreadPoolExecutor(max_workers=2) as ex:
    for link in li:

        futures.append(ex.submit(get_content,link))

for future in futures:
    print(future.result())
Run Code Online (Sandbox Code Playgroud)

请记住,将启动两个 Firefox 实例。

注意:您可能想使用无头浏览器(例如,PhantomJs而不是 Firefox)。