Python 在Selenium中一次加载多个URL
我有一个返回URL列表标题的代码。因为在返回标题之前,我必须等待加载的URL更新,所以我想知道是否有一种方法可以一次加载多个URL并同时返回两个标题 代码如下:Python 在Selenium中一次加载多个URL,python,linux,selenium,Python,Linux,Selenium,我有一个返回URL列表标题的代码。因为在返回标题之前,我必须等待加载的URL更新,所以我想知道是否有一种方法可以一次加载多个URL并同时返回两个标题 代码如下: from pyvirtualdisplay import Display from time import sleep import sys reload(sys) sys.setdefaultencoding('utf-8') from selenium import webdriver from selenium.common.ex
from pyvirtualdisplay import Display
from time import sleep
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.firefox.options import Options
display = Display(visible=0, size(800,600))
display.start()
urlsFile = open ("urls.txt", "r")
urls = urlsFile.readLines()
driver = webdriver.Firefox(executable_path='/usr/local/lib/geckodriver/geckodriver')
driver.set_page_load_timeout(60)
for url in urls:
try:
driver.get(url)
sleep(0.8)
print(driver.title)
except TimeoutException as e:
print("Timeout")
如果我尝试这样做:
driver = webdriver.Firefox(executable_path='/usr/local/lib/geckodriver/geckodriver')
driver2 = webdriver.Firefox(executable_path='/usr/local/lib/geckodriver/geckodriver')
for url in urls:
try:
driver.get(url)
driver2.get(url)
sleep(0.8)
print(driver.title)
print(driver2.title)
except TimeoutException as e:
print("Timeout")
driver2获取的URL与driver1获取的URL相同。有没有可能让driver2获得下一行的URL,这样就可以在不浪费时间的情况下加载这两个URL
from multiprocessing.pool import Pool
# read URLs into list `urls`
with open("urls.txt", "r") as urlsFile:
urls = urlsFile.readlines()
# a function to process a single URL
def my_url_function(url):
# each proc uses it's own driver
driver = webdriver.Firefox(executable_path='/usr/local/lib/geckodriver/geckodriver')
driver.get(url)
print("Got {}".format(url))
# a multiprocessing pool with 2 threads
pool = Pool(processes=2)
map_results_list = pool.map(my_url_function, urls)
print(map_results_list)
本例使用python的多处理模块实际同时处理2个URL——当然,您可以在设置池时更改进程数
pool.map()
函数接受一个函数和一个列表,并在列表上迭代,将每个项发送给函数,并在其自己的进程中运行每个函数调用
更改
my\u url\u function()
函数以执行实际需要的操作,但不要在多进程函数中共享资源-让每个函数生成自己的驱动程序以及函数可能需要的任何其他内容。有些东西可以跨并发函数共享,但完全不共享更安全 当我这样做时,等待使用Javascript生成标题是不起作用的,因此标题总是“正在加载…”而且,在池重复之前还有很长的等待时间。