我试图从html文件中抓取数据。具体来说,我需要输入中变量的值。下面是一个输入的例子,以及到目前为止我试图做的事情(我特别想得到“数据-信息-值”):
输入:
<input type="username" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="current-username" spellcheck="false" tabindex="0" aria-label="Enter your username" name="usernamefield" autocapitalize="off" dir="ltr" data-initial-dir="ltr" data-initial-value="trying to get this" badinput="false">
我的代码:
<script>
String uname = document.getElementById('usernamefield').value
</script>
发布于 2020-03-05 18:08:59
您可以使用getAttribute
注释:选择输入元素的 document.getElementById('usernamefield')
,但是该输入元素上有id
属性。要么添加id
,要么使用任何其他方式进行选择。
const input = document.querySelector('input')
console.log(input.getAttribute('data-initial-value'))
<input type="username" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="current-username" spellcheck="false" tabindex="0" aria-label="Enter your username" name="usernamefield" autocapitalize="off" dir="ltr" data-initial-dir="ltr" data-initial-value="trying to get this" badinput="false">
由于您需要的属性以data
作为前缀,所以可以使用dataset
获得它。注意,当您使用dataset
时,属性名称将转换为camelCase。例如,initial-value
将转换为initalValue
const input = document.querySelector('input')
console.log(input.dataset.initialValue)
<input type="username" class="whsOnd zHQkBf" jsname="YPqjbf" autocomplete="current-username" spellcheck="false" tabindex="0" aria-label="Enter your username" name="usernamefield" autocapitalize="off" dir="ltr" data-initial-dir="ltr" data-initial-value="trying to get this" badinput="false">
发布于 2022-03-03 15:31:01
这有点晚了,但是对于每个需要它的人来说。
Use可以使用querySelector
/querySelectorAll
。
document.querySelector("div[jsname='something']")
您还可以在[]
中编写您想要的每个属性,比如data-attributes
。
希望我能帮上忙
https://stackoverflow.com/questions/60551567
复制相似问题