繁体   English   中英

使用Jsoup从特定类获取所有href值

[英]Use Jsoup to get all href values from a specific class

我试图解析我的大学网站,以从主站点获取新闻列表(标题+链接)。 但是,当我尝试解析一个完整的网站时,我正在寻找的链接嵌套在其他类,表等的深处。这是我尝试使用的代码:

String url = "http://www.portal.pwr.wroc.pl/index,241.dhtml";
    Document doc = Jsoup.connect(url).get();
    Elements links = doc.select("table.cwrapper .tbody .tr td.ccol2 div.cwrapper_padd div#box_main_page_news.cbox.grey div#dyn_main_news.cbox.padd2 div.nitem table.nitemt .tbody .tr td.nitemcell2 span.title_1");
    ArrayList <String> listOfLinks = new ArrayList <String> ();
    int counter = 0;


    for (Element link : links) {

        listOfLinks.add(link.text());

    }

但这是行不通的。 如果将每个链接都放在以下位置,是否有更好的方法来获取所有这些链接的href值和标题:

<span class = "title_1">
    <a href="Link Adress">Link Title</a>
</span>

也许某种循环会遍历所有这些标签并从中获取值?

感谢帮助 :-)

您的主要问题是,您要查找的信息并不存在于您使用的URL中,而是存在于http://www.portal.pwr.wroc.pl/box_main_page_news,241.dhtml?limit=10处
您应该先获得该页面,然后再使用它(这是气垫船和安德烈·沃尔贡的答案的结合)-

String url = "http://www.portal.pwr.wroc.pl/box_main_page_news,241.dhtml?limit=10";
String baseURL = "http://www.portal.pwr.wroc.pl/";
Document doc = Jsoup.connect(url).get();
Elements links = doc.select(".title_1 > a");
for (Element link : links) {
    System.out.println("Title - " + link.text());
    System.out.println(baseURL + link.attr("href"));
}

您需要找到最简单的唯一选择器来选择正确的元素。 在您的情况下,解决方案非常简单:

doc.select(".title_1 > a")

为什么不简单做doc.select("a[href]"); 然后在选择返回的元素中的每个元素上调用.attr("href").text()

例如:

String path = "http://www.portal.pwr.wroc.pl/index,241.dhtml";
int timeoutMillis = 10 * 1000;
try {
    URL url = new URL(path);
    Document doc = Jsoup.parse(url, timeoutMillis);

    Elements selections = doc.select("a[href]");
    String format = "%-40s %s%n";
    for (Element element : selections) {
        System.out.printf(format, element.attr("href"), element.text());
    }

} catch (IOException e) {
    e.printStackTrace();
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM