[英]jsoup how to select from div attribute
如何從此代碼中選擇網址
<div class="main_news_lp_img3"
onclick="location.href='?news_view=77f1f3883c4ceac3'"
style="background-image: url('uploads/resize2/61b96f91b599c754461eca5891a87951.JPG');">
</div>
我想選擇url()
內容-此部分
uploads/resize2/61b96f91b599c754461eca5891a87951.JPG
就像這樣(偽):
編輯:
htmlDocument = Jsoup.connect(HtmlUrl).get();
Elements articles = htmlDocument.select(DIV);
String url = null;
for (Element article : articles) {
Element element = article.select(DIV).first();
if (element.attr(style) != null) {
url = element.attr(style);
}
}
使用Jsoup,您將無法選擇style
屬性的特定“元素”。 您必須閱讀整個屬性,然后自己解析內容:
Document doc = Jsoup.connect("your-url").get()
// select all "div" elements with a class name "main_news_lp_img3"
for (Element el : doc.select("div.main_news_lp_img3")) {
// get the "style" attribute value
String style = el.attr("style");
// parse the url from the attribute
String url = StringUtils.substringBetween(style, "background-image: url('", "')");
// do something with url...
}
在這里,我使用來自Apache commons-lang的 StringUtils.substringBetween
,但您也可以使用正則表達式或實現自己的substringBetween
方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.