我正在寻找一个 html 解析器,可以搜索和替换 anchor 标记,例如
ex
<a href="/ima/index.php">example</a>
to
<a href="http://www.example.com/ima/index.php">example</a>
更新:
我的代码与 jsoup 但不工作
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import com.google.common.collect.ImmutableList;
import com.google.common.net.InternetDomainName;
public class test {
public static void main(String args[]) throws IOException {
Document doc = Jsoup.connect("http://www.google.com").get();
String html =doc.outerHtml().toString();
// System.out.println(html);
Elements links = doc.select("a");
for (Element link : links) {
String href=link.attr("href");
if(href.startsWith("http://"))
{
}
else
{
html.replaceAll(href,"http://www.google.com"+href);
}
}
System.out.println(html);
}
}
最佳答案
此代码将文档中的相对链接更改为代码使用 jsoup 库的绝对链接
private void absoluteLinks(Document document, String baseUri) {
Elements links = document.select("a[href]");
for (Element link : links) {
if (!link.attr("href").toLowerCase().startsWith("http://")) {
link.attr("href", baseUri+link.attr("href"));
}
}
}
关于java - html解析器使用java搜索和替换一些值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4844802/