首页 > 解决方案 > 如何使用 python 和 selenium 从脚本标签中获取变量?

问题描述

我正在尝试获取图表数据并发现数据存储在脚本标记中。在此之前还有许多其他脚本标签,我想访问 var line1 来获取日期和值。这可能吗?

这是html:

<script type="text/javascript">
    $J(document).ready(function(){
    var line1=[["Dec 15 2013 01: +0",46,"1"],["May 26 2020 22: +0",31.883,"1"]];
    g_timePriceHistoryEarliest = new Date();
    if ( line1 != false )
    {
        g_timePriceHistoryEarliest = new Date(line1[0][0]);
        g_timePriceHistoryLatest = new Date(line1[line1.length-1][0]);
    }

    var strFormatPrefix = "$";
    var strFormatSuffix = "";

    g_plotPriceHistory = CreatePriceHistoryGraph( line1, 7, strFormatPrefix, strFormatSuffix );

    pricehistory_zoomMonthOrLifetime( g_plotPriceHistory, g_timePriceHistoryEarliest, g_timePriceHistoryLatest );
});
</script>

我试过了

script = driver.find_element_by_tag_name("script")
scriptText = driver.execute_script("return arguments[0].innerHTML", script)
print(scriptText)

但 scriptText 返回空

完整的 xpath 是

/html/body/div[1]/div[7]/div[2]/script[2]/text()

将不胜感激任何帮助!谢谢!

解决了:

import urllib.request
import re
url=urllib.request.urlopen("yourURL")
content=url.read()
html = content.decode('utf-8')
var_re = re.compile(r'var line1=\[(.+)\]')
date_match = var_re.findall(html)
print (date_match)

标签: javascriptpythonselenium

解决方案


由于您要提取的数据在 HTML 本身中,因此您不需要使用 selenium。您可以使用requests库和re库直接从 HTML 中提取它。这是用于从您提供的示例 HTML 中提取数据的正则表达式代码。它返回一个str包含您似乎想要的日期和值的列表。

由于您没有提供 URL,因此您需要自己编写该requests部分的代码。

html = """<script type="text/javascript">
$J(document).ready(function(){
var line1=[["Dec 15 2013 01: +0",46,"1"],["May 26 2020 22: +0",31.883,"1"]];
g_timePriceHistoryEarliest = new Date();
if ( line1 != false )
{
    g_timePriceHistoryEarliest = new Date(line1[0][0]);
    g_timePriceHistoryLatest = new Date(line1[line1.length-1][0]);
}

var strFormatPrefix = "$";
var strFormatSuffix = "";

g_plotPriceHistory = CreatePriceHistoryGraph( line1, 7, strFormatPrefix, strFormatSuffix );

pricehistory_zoomMonthOrLifetime( g_plotPriceHistory, g_timePriceHistoryEarliest, g_timePriceHistoryLatest );
});</script>"""

var_re = re.compile(r'var line1=\[(.+)\]')
date_match = var_re.findall(html)

print(date_match)

Output:
['["Dec 15 2013 01: +0",46,"1"],["May 26 2020 22: +0",31.883,"1"]']

推荐阅读