我正在寻找一个html解析器,可以搜索和替换锚标签,如
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);
}
}
发布于 2012-11-19 16:34:58
此代码将文档中的相对链接更改为绝对链接
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"));
}
}
}
发布于 2011-03-14 16:03:35
package javaapplication4;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
/**
*
* @author derek
*/
public class Main
{
/**
* @param args the command line arguments
*/
public static void main(String[] args)
{
try
{
Document document = Jsoup.connect("http://www.google.com").get();
Elements elements = document.select("a");
for (Element element : elements)
{
element.baseUri();
}
System.out.println(document);
}
catch (Exception e)
{
e.printStackTrace(System.err);
}
}
}
发布于 2011-01-30 19:04:42
您可以使用String.replaceAll()和一个匹配
<a href="/
要查找所有相对链接,请执行以下操作。
html = html.replaceAll("<a href=\"/", "<a href=\"http://www.google.com/\"");
https://stackoverflow.com/questions/4844802
复制相似问题