使用 JSOUP 进行网页抓取
Web Scraping with JSOUP
我是抓取新手。我正在尝试使用 JSOUP 从网站上抓取数据。我想从 <div>
、<span>
、<p>
等标签中抓取数据。谁能告诉我该怎么做?
勾选this。一个基本的例子:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Test {
public static void main(String[] args) throws Exception {
String url = "";
Document document = Jsoup.connect(url).get();
String text = document.select("div").first().text();
System.out.println(text);
Elements links = document.select("a");
for (Element link : links) {
System.out.println(link.attr("href"));
}
}
}
这将首先打印页面上第一个div
的文本,然后打印出页面上所有链接(a
)的所有url。
要获得具有特定 class 的 div,请执行 Elements elements = document.select("div.someclass")
要获取具有特定 ID 的 divs,请执行 Elements elements = document.select("div#someclass")
如果您想遍历所有选定的元素,请执行以下操作:
for (Element e:elements) {
System.out.println(e.text());
//you can also do other things.
}
我是抓取新手。我正在尝试使用 JSOUP 从网站上抓取数据。我想从 <div>
、<span>
、<p>
等标签中抓取数据。谁能告诉我该怎么做?
勾选this。一个基本的例子:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
public class Test {
public static void main(String[] args) throws Exception {
String url = "";
Document document = Jsoup.connect(url).get();
String text = document.select("div").first().text();
System.out.println(text);
Elements links = document.select("a");
for (Element link : links) {
System.out.println(link.attr("href"));
}
}
}
这将首先打印页面上第一个div
的文本,然后打印出页面上所有链接(a
)的所有url。
要获得具有特定 class 的 div,请执行 Elements elements = document.select("div.someclass")
要获取具有特定 ID 的 divs,请执行 Elements elements = document.select("div#someclass")
如果您想遍历所有选定的元素,请执行以下操作:
for (Element e:elements) {
System.out.println(e.text());
//you can also do other things.
}