簡體   English   中英

如何使用 selenium 和 python 從網站獲取工具提示文本,其中文本來自 javascript

[英]How can I get the tooltip text from a website using selenium and python where the text comes from a javascript

我正在嘗試獲取工具提示文本,該文本顯示我 hover 多久以前玩過游戲https://www.leagueofgraphs.com/summoner/eune/AnFrey99在此處輸入圖像描述 ] 1

在 html 代碼中,它不顯示文本,我認為它來自 javascript,每行在 tr 標簽內都有一個腳本,但到目前為止我無法獲得 var newTooltipData 的值。


    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')

If you hover the div, JavaScript will append a new div to the website with the ID 'tooltip' (full source of the function here ):

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

因此 Selenium 可以在 hover 之后找到這個新的 div id = "tooltip",它調用了這個 function。

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)

output:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM