[英]how to web-scrape from a table?
我正在做一個項目,我必須從網站https://lite.ip2location.com進行網絡抓取。 當您進入該站點時,會出現許多div
,每個 div 代表不同的國家/地區。 當您單擊其中一個時,瀏覽器將重定向到該站點上的表格。 該表有一個thead
和tbody
。 我需要訪問tbody
但由於某種原因,我只能從thead
標簽中獲取信息。
這是我的代碼:
public static void main(String[] args) {
final String url = "https://lite.ip2location.com/ip-address-ranges-by-country";
try {
final Document document = Jsoup.connect(url).get();
for (Element element : document.select("div.card-columns div")) {
Elements link = element.select("a");
String redirectUrl = "https://lite.ip2location.com" + link.attr("href");
final Document redirectDoc = Jsoup.connect(redirectUrl).get();
Element table = redirectDoc.select("table").get(0);
for (Element row : table.select("tbody tr")) {
System.out.println(row.text());
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Jsoup 只是從一個 URL 解析 HTML,它不執行 JavaScript 或獲取其他資源,例如 js 或 css 文件。
在具有以 JSON 表示的國家/地區數據的 IP 地址范圍的頁面上,該數據由瀏覽器異步加載,然后使用該數據填充表格。
這里final Document redirectDoc = Jsoup.connect(redirectUrl).get();
你得到了一個 HTML 頁面,其中只包含一個表格模板。 像這樣
<div class="row my-5" style="min-height:500px;">
<div class="col table-responsive">
<table id="ip-address" class="table table-striped table-hover">
<thead>
<tr>
<th width="30%" class="no-sort">Begin IP Address</th>
<th width="30%" class="no-sort">End IP Address</th>
<th width="40%" class="text-right no-sort">Total Count</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
正是您在代碼中解析的這個片段。
因此,有一種可能的解決方案來獲取范圍。
具有津巴布韋 IP 地址范圍的數據位於https://cdn-lite.ip2location.com/datasets/ZW.json
之類的 URL。 文件名與國家代碼 Alpha-2(ZW 代表津巴布韋)匹配。
這些可用國家/地區的代碼可以從https://lite.ip2location.com/ip-address-ranges-by-country
頁面中提取,其中每個國家/地區的<p class="card-text">
標記內都有一個span
標記以繪制標志。
第二類在名稱末尾包含一個代碼(flag-icon- ba )
<div class="card" style="min-height:72px;">
<div class="card-body" style="padding:.85rem;">
<p class="card-text"><span class="flag-icon flag-icon-ba"></span> <a href="/bosnia-and-herzegovina-ip-address-ranges">Bosnia and Herzegovina</a></p>
</div>
</div>
波斯尼亞和黑塞哥維那學士學位。
擁有特定國家/地區的 JSON 數據的 URL,您可以使用 Jsoup 獲取它。
String data = Jsoup
.connect("https://cdn-lite.ip2location.com/datasets/BA.json")
.ignoreContentType(true)
.get().text();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.