首页 > 解决方案 > 如何使用请求获取 Javascript 页面的完整 HTML 内容?

问题描述

我想使用 Python 来检索 JavaScript 后面的一些内容。我有一个结构如下的网站:(为了便于阅读,我添加了换行符):

'<!DOCTYPE html>\n<html lang="ja">\n  <head>\n    <meta charset="utf-8"/>\n    <title>HRMOS CORE Employee</title>\n    
<base href="/"/>\n    <meta name="viewport" content="width=device-width, initial-scale=1"/>\n    
<link rel="icon" type="image/x-icon" href="assets/favicon.ico"/>\n  <link rel="stylesheet" href="styles.ea399ef1dfe4d0c1ba1f.css"></head>\n  
<body class="pol">\n    
<ess-root></ess-root>\n  <script src="runtime-es2015.9968ad6faaffe0609121.js" type="module"></script><script src="runtime-es5.9968ad6faaffe0609121.js" nomodule defer></script><script src="polyfills-es5.1271ae52020e40d8a200.js" nomodule defer></script><script src="polyfills-es2015.04cc7054da2685d59767.js" type="module"></script><script src="main-es2015.07a2df0e93ddc04b405f.js" type="module"></script><script src="main-es5.07a2df0e93ddc04b405f.js" nomodule defer></script></body>\n</html>\n'

实际的 html 内容是一个交互式表格,由前面代码中的 js 脚本呈现。

我正在尝试使用该request模块检索表的内容。我使用了以下代码(我确定授权正在工作,因为请求模块返回状态 200):

from requests_html import AsyncHTMLSession
import lxml.html

session = AsyncHTMLSession()
r = await session.get('https://ess.hrmos.co/', auth=('user', 'password'))
await r.html.arender(wait=10, sleep=10, keep_page=True)
tree = lxml.html.fromstring(r.text)
title_elem = tree.xpath("/html/body/ess-root/core-ui-theme/ess-core-layout/pol-layout/pol-content/ess-employee-list-page/div/div/ess-employee-cards-container/cdk-virtual-scroll-viewport/div[1]/div[1]/a[1]/ess-employee-card/pol-card/div[1]") 
print("title tag:", title_elem.tag)

但即使我在代码中使用了等待,我从中得到的实际 htmlrequest也是空的,其中没有任何内容。有没有办法确保我检索内容?还是我必须使用硒?

标签: javascriptpythonpython-requestslxml

解决方案


推荐阅读