我正在进行递归 url 收获.. 当我在源中找到不以“http”开头的链接时,我会将其附加到当前 url。问题是,当我遇到动态站点时,没有 http 的链接通常是当前 url 的新参数。例如,如果当前 url 类似于 http://www.somewebapp.com/default.aspx?pageid=4088在该页面的源代码中,有一个链接是default.aspx?pageid=2111。在这种情况下,我需要进行一些字符串操作;这就是我需要帮助的地方。
伪代码:
if part of the link found is a contains a substring of the current url
save the substring
save the unique part of the link found
replace whatever is after the substring in the current url with the unique saved part
这在 java 中会是什么样子?有什么不同的想法吗?谢谢。
根据评论,这是我尝试过的:
if (!matched.startsWith("http")) {
String[] splitted = url.toString().split("/");
java.lang.String endOfURL = splitted[splitted.length-1];
boolean b = false;
while (!b && endOfURL.length() > 5) { // f.bar shortest val
endOfURL = endOfURL.substring(0, endOfURL.length()-2);
if (matched.contains(endOfURL)) {
matched = matched.substring(endOfURL.length()-1);
matched = url.toString().substring(url.toString().length() - matched.length()) + matched;
b = true;
}
}
效果不太好..
最佳答案
我认为您的做法是错误的。 Java 有两个类 URL
和 URI
,它们能够比“string bashing”解决方案更准确地解析 URL/URL 字符串。例如 URL 构造函数 URL(URL, String)
将在现有对象的上下文中创建一个新的 URL
对象,而无需担心该字符串是绝对 URL 还是相对 URL。你会像这样使用它:
URL currentPageUrl = ...
String linkUrlString = ...
// (Exception handling not included ...)
URL linkUrl = new URL(currentPageUrl, linkUrlString);
关于java - url 收割机字符串操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13002202/