gpt4 book ai didi

javascript - 如何从网页将javascript值加载到python中?

转载 作者:行者123 更新时间:2023-12-03 00:01:55 26 4
gpt4 key购买 nike

当我检查网页上的代码时,我可以看到 html 和 javascript。我使用 Beautiful Soup 来导入和解析 html,但是有很大一部分是用 javascript 编写的,它从可编程逻辑 Controller (PLC) 中提取变量。使用 Beautiful Soup 加载和解析后,我无法在 python 中找到数据 - 这只是 html 代码。

网页直接读取 PLC,我看到实时值在我面前更新,但我无法直接导入它们。屏幕截图是检查窗口中代码的样子。假设我想导入带有属性 class="on" 的变量 id="aout7",我该怎么做?

Inspect View Source of webpage

最佳答案

网页最好在浏览器中运行。有一些用于远程控制浏览器/浏览器引擎的 API,最流行的一个是 Selenium ,并且它具有 Python 绑定(bind):请参阅 https://pypi.org/project/selenium/ - 该页面包含安装说明:

pip install -U selenium

以及一些介绍性示例,例如发出雅虎搜索的代码片段:

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

browser = webdriver.Firefox()

browser.get('http://www.yahoo.com')
assert 'Yahoo' in browser.title

elem = browser.find_element_by_name('p') # Find the search box
elem.send_keys('seleniumhq' + Keys.RETURN)

browser.quit()

您将需要类似的东西,只需使用 find_element_by_id ( https://selenium-python.readthedocs.io/locating-elements.html ),并使用元素的 text 属性来读取其内容。

关于javascript - 如何从网页将javascript值加载到python中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55130720/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com