如何使用 selenium 和 python 从网站获取工具提示文本,其中文本来自 javascript

时间:2021-02-10 16:28:53

标签: javascript python html selenium

我正在尝试获取当我将鼠标悬停在游戏已玩多长时间上时显示的工具提示文本 https://www.leagueofgraphs.com/summoner/eune/AnFrey99 enter image description here]1

在 html 代码中,它没有显示文本,我认为它来自 javascript 并且每一行在 tr 标签内都有一个脚本,但到目前为止我无法获得 var newTooltipData 的值。< /p>


    var newTooltipData = {"match-2733966814": (new Date(1612964002882).toLocaleDateString() + " " + new Date(1612964002882).toLocaleTimeString()) + " - 31min 48s"};
    if (window.tooltipData) {
        window.tooltipData = Object.assign(window.tooltipData, newTooltipData);
    } else {
        window.tooltipData = newTooltipData;
    }

我想获得每一行的确切日期以及我已经完成的其他信息。 这是我的代码和我的尝试。
driver_second = webdriver.Firefox(executable_path=DRIVER_PATH)
driver_second.get("https://www.leagueofgraphs.com/summoner/eune/"+'AnFrey99')
time.sleep(5)
accept_button=driver_second.find_element_by_xpath("/html/body/div[3]/div/div/div[3]/div[1]/button[2]")
accept_button.click()
tabel=driver_second.find_element_by_xpath("//table[@class='data_table relative recentGamesTable']")
rows=tabel.find_elements_by_xpath("tbody/tr")
for row in rows:
    elements=row.find_elements_by_xpath("td")
    if(len(elements)>1):
            script=row.find_element_by_xpath("script")
            data=elements[2].find_element_by_xpath("a/div[3]")
            data=script.get_property('innerHTML')

1 个答案:

答案 0 :(得分:1)

如果您将鼠标悬停在 div 上,JavaScript 会向网站添加一个 ID 为 'tooltip'(函数 here 的完整源代码)的新 div:

var TooltipManager = (function () {
    [...]
            var tooltipElement = $('#tooltip');
            if (!tooltipElement.length) {
                $('body').append('<div id="tooltip"></div>'); #New Div appended
                [...]

因此当你将鼠标悬停在调用这个函数的 div 上时,Selenium 可以找到这个新的 div id = "tooltip"。

from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.common.action_chains import ActionChains    
import time
    
driver_second = webdriver.Firefox(executable_path=DRIVER_PATH)
driver_second.get('https://www.leagueofgraphs.com/summoner/eune/AnFrey99')
time.sleep(3)

infos = driver_second.find_elements_by_class_name('gameDate')

for i in infos:
    hover = ActionChains(driver_second).move_to_element(i)
    hover.perform()
    time.sleep(1)
    DateofGame = driver_second.find_element_by_id('tooltip').text
    print(DateofGame)

输出:

10.2.2021 14:33:22 - 31min 48s
10.2.2021 14:02:55 - 20min 47s
29.1.2021 04:12:09 - 29min 13s
29.1.2021 03:23:24 - 34min 54s
29.1.2021 02:44:22 - 32min 46s
29.1.2021 01:35:22 - 32min 48s
28.1.2021 23:23:19 - 24min 35s
10.1.2021 01:12:34 - 21min 8s
8.1.2021 22:27:35 - 21min 4s
8.1.2021 22:08:01 - 14min 51s