javascript - 如何使用 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)
解决方案
由于您要提取的数据在 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"]']
推荐阅读
- android - 离子本机串行返回设备未找到
- clojure - clojure - 是素数吗?质数
- laravel - 如何在 Laravel 中对请求使用自定义翻译?
- django - Selenium 停止与 Firefox 合作,与 Safari 合作
- csv - 如何使用 exiftool 将文件重命名为 CSV 导入文件中包含的新名称
- java - RandomAccessFile 不适用于 Minecraft Forge
- mongodb - docker-compose 抑制 mongodb 输出
- c# - 如何使用 SqlDataReader 从 C# 中的 SQL Server 数据库中检索多行?
- swift - 分段错误:Xcode 升级后为 11
- opengl - 应用投影 OpenGL 时输出失真