【发布时间】:2021-01-02 14:20:08
【问题描述】:
作为 Python 和 Selenium 的初学者,我尝试编写自己的脚本来从博彩网站 (Winamax) 抓取数据并将其保存到数据集中。我的脚本使用 Selenium 模块的 find_elements_by_tag_name('div') 函数来查找所有带有 div 标签名称的元素。在我的情况下,搜索 div 而不是 scan(如第一次推荐,请参阅 this discussion)更方便,因为结果列表的一个元素收集了我需要的表的所有信息。我基本上需要比赛的日期(在元素的开头,例如 MERCREDI 6 JANVIER)、球队(例如 Brest-Nice)、三个投注每场比赛的费率和比赛的时间。这是表格一部分的打印屏幕:
这是我想要获取的数据框:
这种方法的缺点是有很多div标签,这使得我的代码很慢而且效率很低。根据我下面的代码,有什么方法可以加快我的代码,同时保持相同的结果字符串列表?
我在我的代码中包含了一些print() 以查看所有带有div 标签的元素。没有打印的模型大约需要 2 分钟,打印的模型大约需要 4 分钟。
from selenium import webdriver
import re
import time
start = time.time()
#Load script from website
option = webdriver.ChromeOptions()
option.add_argument('--headless')
option.binary_location = r'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe'
end1 = time.time()
browser = webdriver.Chrome(executable_path=r'C:/webdrivers/chromedriver.exe', options=option)
browser.get(r"https://www.winamax.fr/paris-sportifs/sports/1/7/4")
end2 = time.time()
#Select the part of the script where data are stored
span_tags = browser.find_elements_by_tag_name('div')
end25 = time.time()
tags = []
for span_tag in span_tags:
tags.append(span_tag.text)
print(span_tag.text)
print("----------------------------------------------------------------")
print(len(tags))
end3 = time.time()
#Select the element of the list that describe the data we need
pattern = re.compile(r'(?:LUNDI|MARDI|MERCREDI|JEUDI|VENDREDI|SAMEDI|DIMANCHE)')
my_list5 = list(filter(pattern.match,tags))
#Print the indices of the selected element
print([i for i, j in enumerate(tags) if pattern.match(j)])
print("-------------------------------------------------------------------------------------------------------")
#Print the selected element
for m in my_list5:
print(m)
print("----------------------------------------------------------------")
#Select the first element, as it gathers all the necessary information
string=my_list5[0]
string2=string.splitlines()
#Print the executing times between the different tasks
print(end1-start)
print(end2-end1)
print(end25-end2)
print(end3-end25)
【问题讨论】:
-
您想从站点检索哪些确切信息?从您的代码看来,您正在打印页面上所有
span元素的代码,但我不确定您想要实现什么。 -
我更新了我的问题:我需要日期、时间、球队和投注率。