javascript - 在 bash 脚本中获取带有 javascript 元素的 HTML 页面
问题描述
我正在尝试在 bash 脚本中获取包含一些流量统计信息的网站。此 html 页面上的实际值是用 javascript 编写的。所以当用浏览器查看网页时,我可以看到实际值。但是在查看 html 代码时,例如使用 curl,值的位置如下所示:
<div>
<div class="agile_float">
<script type="text/javascript">
dw(IDS_statistics_aglie_month_volume_used);
dw(common_colon);
</script>
</div>
<div id="month_used_value" class="agile_td_ltr"></div>
</div>
感兴趣的值将位于 ID 为“month_used_value”的现在为空的 div 中。我已经找到了一些使用 PhantomJS 的提示,但我不确定这是否真的是要走的路?!有没有一种简单的方法可以从 bash 脚本中收集这些值?
解决方案
您所做的称为 Web Scraping - Internet 上有大量信息和工具如何做到这一点。分享一下我的方法:
1. 正如 Hugo 所指出的,您需要做的第一件事是从网站读取DOM。
为此,您肯定需要一个无头浏览器。好消息是许多前端浏览器也支持无头模式。例如,如果您已Google Chrome
安装,您也可以在无头模式下从命令行运行它,以获取渲染页面的整个(动态)内容。例如在 Mac 上:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --headless --dump-dom --disable-gpu "https://www.google.com"
2. 一旦你得到渲染的 html 内容,你需要可靠地处理它。
sed
使用/ /etc 等面向行的工具解析 HTML(以及任何嵌套数据格式)awk
很容易出错,因此您需要找到能够从 HTML 中解析(提取)数据的实用程序,该实用程序支持 html。
我使用jtm
(由我开发)。这是一个往返(往返)的无损转换HTML/XML
器JSON
。将 HTML 转换为 JSON 的原因很简单 - JSON 是(最)广泛使用的数据模型,并且现在有大量的 JSON 解析器可用。
一旦它被转换为 JSON,您就可以使用任何工具从 JSON 中提取所需的信息 - 同样,有很多可用的离线工具,但我使用的是我jtc
的 - 它非常快(但这只对非常大的 JSON 很重要)而且jtc
非常简单提取任何 JSON 信息。
例如,以下从 stackoverflow 中提取了前面的问题列表:
bash $ /Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --headless --dump-dom --disable-gpu "https://stackoverflow.com/questions" 2>/dev/null | jtm | jtc -w'[class]:<question-hyperlink>:[-3]><P:'
"Component LoginContainerComponent is not part of any NgModule or the module has not been imported into your module"
"Removing an object with attributes from a list?"
"Is there a Predicate for operator instanceof?"
"How to use multiple document processor in vespa.ai in separate search chain?"
"How do I load an external JS library in Svelte/Sapper?"
"Why do gcc and clang place custom-sectioned const-funcptr symbols into writable sections when compiling with -fpic?"
"How does one solve “ 'CMySQLCursor' object has no attribute 'keys'”?"
"css video iframe good practice wordpress"
"auto complete address and navigate to that place"
"How do I trace an exact or find a specific value in a matplotlib graph?"
"Swift 5 How to get JSON multilayer data to append?"
"Excel wrong data format"
"Converting React function component to class component in React-JS"
"Can't Move PTZ Camera using ONVIF Protocol -Python Client"
"Can a TypeScript HttpClient accept a string that is not explicitly formatted as JSON?"
bash $
提取所需信息后,您可以将构建的命令行合并到 bash 脚本中。
推荐阅读
- python-3.x - GET 请求中的变量替换
- c# - “wwwroot”文件夹中的某些文件未在 ASP.NET Core Web 部署中发布
- vba - 如何将单元格边框动态格式化为用户类型?
- ios - UITableViewCell - 无法同时满足约束
- amazon-web-services - AWS 通配符证书的子域问题
- ruby-on-rails - 为设计中的额外字段添加自定义错误消息
- c# - 为什么在单个页面中使用多个 foreach 循环导致第一个 foreach 与 c# 重复?
- swift4 - 如何将 ARReferenceImage 放入 Core Data?
- angular - 防止选中单选按钮但无法从 ionSelect ion-radio 获取 RadioButton 组件对象
- angular - 异步测试执行问题