![](/img/trans.png)
[英]Get the url of the background-image from an div elment with javascript
[英]JavaScript/Jsoup - Get background-image url from “i class”
所以我在我的应用程序的webview中加载一个网页,并且有一个HTML i class="img profimage"
,它有一个背景图像网址,这是我的目标......
我想用JavaScript或使用Jsoup来获得目标...
我到目前为止用Jsoup尝试的是这样的:
public class GetImage extends AsyncTask<String, String, String> {
protected String doInBackground(String... strings) {
Document document = null;
try {
document = Jsoup.connect(url).get();
} catch (IOException e) {
e.printStackTrace();
}
String temp = document.select("i.img.profpic").first().getElementsByAttribute("style").toString();
return temp.substring(temp.indexOf("(") + 1, temp.indexOf(")"));
}
protected void onPostExecute(String result) {
Log.d("ChatScreen", result);
Toast.makeText(ChatScreen.this, result, LENGTH_SHORT).show();
}
}
但我正在接受NPE ...我不知道如何使用JavaScript获取i类的背景图像网址...我可以在网上找到很多关于如何使用ids
获取div
的示例
页面的HTML结构与此类似:
<div ....>
<div ....>
<i class="img profimage" style="background-image: url("url here");"/>
</div>
</div>
检查这个答案可能会有效,但我没试过。 JS函数在evaluateJavascript()中编写,它将读取样式属性,然后您可以使用substring方法来获取URL。
webview.evaluateJavascript(
"(function() { return (document.getElementsByTagName('i')[index].getAttribute('style')); })();",
new ValueCallback<String>() {
@Override
public void onReceiveValue(String html) {
Log.d("HTML", html);
// now use substring to get url.....
}
});
希望这对你有所帮助。
引用这个答案,您可以尝试类似下面的内容(假设它是具有类profimage
的唯一/第一个元素,否则更改索引,即[n]
,其中n
是索引)。 或者,只需给元素一个唯一的id
并使用document.getElementById('imgid')
并删除[0]
。 将其包含在函数中,以防您想要在特定事件上调用它。
function getUrl() {
var img = document.getElementsByClass('profimage'),
style = img[0].currentStyle || window.getComputedStyle(img[0], false),
bi = style.backgroundImage.slice(5, -2);
return bi;
}
切片将删除URL本身后的URL url("
之前和之后")
。 请注意,这将返回完整的URL。
如果这不起作用,您可以尝试使用style = img.style,
代替上面代码中的较长表达式,因为背景图像在元素本身中添加了内联css( <i ... style="background-image: url("url here");"/>
。 这将返回内联样式的url,在本例中为url here
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.