如何在python中使用webdriver提高执行时间
在下面的代码中,我试图在不同的url中导入几场足球比赛的赔率。我使用webdriver.firefox导航到每个网页。我的问题是执行时间太长 在我的例子中,有25个url链接,但在第一次测试中,我只使用了4个url链接。执行时间为2,37分钟,因此25个url链接大约需要20分钟。时间太多了。 所以我想知道这次是否有可能改进和优化 这是我的密码:如何在python中使用webdriver提高执行时间,python,loops,selenium-webdriver,Python,Loops,Selenium Webdriver,在下面的代码中,我试图在不同的url中导入几场足球比赛的赔率。我使用webdriver.firefox导航到每个网页。我的问题是执行时间太长 在我的例子中,有25个url链接,但在第一次测试中,我只使用了4个url链接。执行时间为2,37分钟,因此25个url链接大约需要20分钟。时间太多了。 所以我想知道这次是否有可能改进和优化 这是我的密码: #!/usr/bin/python3 # -*- coding: utf-8 -*- from selenium import webdrive
#!/usr/bin/python3
# -*- coding: utf-8 -*-
from selenium import webdriver
import statistics as stat
import numpy as np
driver = webdriver.Firefox()
url = 'https://www.coteur.com/cotes-foot.php'
driver.get(url)
#Store url associated with the soccer games
url_links = []
for i in driver.find_elements_by_xpath('//a[contains(@href, "match/cotes-")]'):
url_links.append(i.get_attribute('href'))
driver.close()
print(len(url_links))
for l in range(0, 4):
driver = webdriver.Firefox()
driver.get(url_links[l])
#Store odds into table
odds = []
header = []
for i in driver.find_elements_by_xpath('//button[contains(@class, "btn btn-default btn-xs btncote")]'):
odds.append(i.text)
for i in driver.find_elements_by_xpath('//th[contains(@width, "20%")]'):
header.append(i.text)
rows = int(len(odds)/3)
columns = 3
odds = [float(i) for i in odds]
odds = np.array(odds)
header = np.array(header)
odds = odds.reshape(rows, columns)
print(odds, '\n')
driver.close()
以下是输出:
hao@hao-ThinkPad-T420:~$ time ./parallel.py
25
[[1.28 5.2 7.25]
[1.33 4.7 6.55]
[1.33 4.6 6.5 ]
[1.37 4.4 6. ]
[1.37 4.4 6. ]
[1.3 4.6 7. ]
[1.31 4.5 6.7 ]
[1.31 4.7 6.3 ]
[1.27 4.8 7. ]
[1.26 4.8 6.75]
[1.25 4.9 6.75]
[1.24 4.7 6.75]]
[[1.8 3.58 3.77]
[1.8 3.35 3.9 ]
[1.8 3.4 3.7 ]
[1.8 3.36 3.62]
[1.8 3.35 3.55]
[1.8 3.35 3.5 ]
[1.73 3.45 3.55]
[1.73 3.4 3.6 ]
[1.73 3.4 3.6 ]
[1.76 3.3 3.45]
[1.72 3.35 3.55]]
[[3.5 3.7 1.8 ]
[2.98 3.51 1.96]
[2.95 3.5 1.95]
[2.91 3.5 1.96]
[3.35 3.7 1.75]
[3.22 3.6 1.81]
[3.25 3.6 1.78]
[3.3 3.75 1.73]
[3.3 3.65 1.73]
[3.3 3.6 1.72]
[2.5 3.1 2.2 ]]
[[3.3 3.5 2.32]
[3.4 3.55 2.25]
[3.4 3.55 2.25]
[3.4 3.55 2.25]
[3.4 3.55 2.25]
[3.35 3.35 2.3 ]
[3.25 3.45 2.22]
[3.25 3.4 2.22]
[3.3 3.45 2.15]
[3.3 3.25 2.2 ]
[3.15 3.3 2.17]]
real 2m37,742s
user 1m1,416s
sys 0m11,797s
我不会说法语,但我猜你试图做的是违反他们的TOS。你应该仔细阅读,并确保它不是。话虽如此,您不需要在每次循环期间关闭和重新打开驱动程序。只需保留单个驱动程序实例并使用它,直到完成所有迭代,然后关闭它。这应该会节省你一点时间。更大的时间节省是并行运行。您可以运行脚本的第一部分并将URL写入文件。然后创建一个以URL作为输入的数据驱动测试,并为每个URL启动一个浏览器。根据运行它的机器的不同,每个URL每个浏览器应该有一个内核,而且速度应该快得多。谢谢你的回答。我删除了循环中的line driver.close(),实际上它的速度快了一点。不幸的是,我有25页要打开,当我不关闭它们的时候,我的电脑崩溃了,所以我正在尝试第二种方法,也就是说并行