我有一个小问题,我使用axios将我的React应用程序发送到网站,我得到了html响应:responseData.data。 但现在我想获取responseData.data中特定div的内容。 例如这一个:
<!DOCTYPE html>
<html class="devise-layout-html">
<head prefix="og: http://ogp.me/ns#">
</head>
<body class="ui_charcoal login-page application navless" data-page="sessions:new">
<div class="tab-content">
<div class="active login-box tab-pane" id="ldapmain" role="tabpanel">
<div class="login-body">
<form id="new_ldap_user" class="gl-show-field-errors" action="/users/auth/ldapmain/callback" accept-charset="UTF-8" method="post"><input name="utf8" type="hidden" value="✓" />
<input type="hidden" name="authenticity_token" value="V8qeuk9QAYk51gorLAobEYGvCMMuyPpuUKXAwtBm2Zw1b1/7BVibiPhRWI7aVrQBa2p+CkKLGCEbQV/UIxZmkA==" /><div class="form-group">
<label for="username">LDAP Username</label>
<input type="text" name="username" id="username" class="form-control top" title="This field is required." autofocus="autofocus" required="required" />
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" name="password" id="password" class="form-control bottom" title="This field is required." required="required" />
</div>
<div class="remember-me checkbox">
<label for="remember_me">
<input type="checkbox" name="remember_me" id="remember_me" value="1" />
<span>Remember me</span>
</label>
</div>
<input type="submit" name="commit" value="Sign in" class="btn-save btn" />
</form>
</div>
</div>
</div>
</body>
</html>
我希望能够访问这些数据:<input type="hidden" name="authenticity_token" value="V8qeuk9QAYk51gorLAobEYGvCMMuyPpuUKXAwtBm2Zw1b1/7BVibiPhRWI7aVrQBa2p+CkKLGCEbQV/UIxZmkA==" />
(值)。可能吗 ?感谢
答案 0 :(得分:1)
试试Cheerio。像jQuery,但为服务器设计。
答案 1 :(得分:1)
您也可以尝试将其解析为XML。例如使用此xml parser
编辑:
在您的情况下,从特定标记属性获取值的最快方法是使用正则表达式:例如
/(<input type="hidden" name="authenticity_token")((.|\s|\v)*?)(\/>)/
允许您从输入中提取value
属性
const htmlDocumentString = '...<input type="hidden" name="authenticity_token" value="V8qeuk9QAYk51gorLAobEYGvCMMuyPpuUKXAwtBm2Zw1b1/7BVibiPhRWI7aVrQBa2p+CkKLGCEbQV/UIxZmkA==" />...'
const reg = /(<input type="hidden" name="authenticity_token")((.|\s|\v)*?)(\/>)/
// The second group of regex match should contain value="..."
const vAttr = reg.exec(htmlDocumentString)[2]
// Time to extract content of the value attribute.
// The fastest way by using substring and character indexes like so
const value = vAttr.substring(vAttr.indexOf('"') + 1, vAttr.lastIndexOf('"'))
console.log(value) // [string] "V8qeuk9QAYk51gorLAob..."
答案 2 :(得分:-1)
是的,您可以将所有文件解析为字符串并获取您的价值,是的,这有点难。但是对于real,只获取值并将其保存到React State或Redux State,然后将状态值添加到输入值!这就是全部!
P.S。最好问问做这个惊人的api的男人! :)