- 確保安裝CefSharp軟件包,相關安裝步驟可以自行搜索
- CefSharp相關信息可在網上搜索,在這裏主要使用到它作爲瀏覽器的功能
- 思路:
- 使用CefSharp打開相關網頁,以http://fundf10.eastmoney.com/jjjz_004719.html爲例,代碼如下:
private void btn_Click(object sender, RoutedEventArgs e)
{
web.Address = textBox.Text;
}
- 相關網頁打開之後可發現其歷史基金數據在以下HTML代碼中:
<div id="jztable">
<table class="w782 comm lsjz">
<thead>
<tr>
<th class="first">淨值日期</th>
<th>單位淨值</th>
<th>累計淨值</th>
<th>日增長率<img title="" id="jjjzTip" style="position: relative;top: 3px;left: 3px;" src="http://j5.dfcfw.com/image/201307/20130708102440.gif" data-placement="bottom" data-html="true" data-original-title="日增長率爲空原因如下:<br>1、非交易日淨值不參與日增長率計算(灰色數據行)。<br>2、上一交易日淨值未披露,日增長率無法計算。"></th>
<th>申購狀態</th>
<th>贖回狀態</th>
<th class="tor last">分紅送配</th>
</tr>
</thead>
<tbody>
<tr>
<td>2020-01-23</td>
<td class="tor bold">1.1168
</td>
<td class="tor bold">1.1168</td>
<td class="tor bold red">0.71%</td>
<td>限制大額申購</td>
<td>開放贖回</td>
<td class="red unbold"></td>
</tr>
... ...
<tr>
<td>2019-12-26</td>
<td class="tor bold">1.0519
</td>
<td class="tor bold">1.0519</td>
<td class="tor bold red">0.62%</td>
<td>開放申購</td>
<td>開放贖回</td>
<td class="red unbold"></td>
</tr>
</tbody>
</table>
</div>
- 在分析網頁的HTML內容發現,其歷史基金一次性獲取並不完整,需要通過AJAX反覆獲取。通過需要使用CefSharp的JS異步操作技術,模擬網頁按鍵操作即可實現自動翻頁功能。部分代碼如下:
script =
$"var btns = pagebar.getElementsByTagName(\"label\");" +
$"for(var i=0; i<btns.length; i++)" +
"{" +
$"if(btns[i].getAttribute(\"value\")=={(next).ToString()})" +
"{" +
"btns[i].click();" +
"break;" +
"}" +
"}";
web.GetBrowser().MainFrame.ExecuteJavaScriptAsync(script);
- 翻頁完成後,通過讀取當前頁面數據即可獲得相關歷史基金數據。代碼如下:
web.GetBrowser().MainFrame.GetSourceAsync().ContinueWith(x =>
{
if (!x.IsFaulted)
{
Dispatcher?.Invoke(() => {
_htmlDocument.LoadHtml(x.Result);
var v = _htmlDocument.GetElementbyId("jztable");
if (v != null)
{
if (v.SelectNodes("table").Count != 0)
{
var table = v.SelectNodes("table");
if (table[0].SelectNodes("tbody").Count != 0)
{
var tr = table[0].SelectNodes("tbody")[0].SelectNodes("tr");
for(int trIdx=0; trIdx < tr.Count; trIdx++)
{
var td = tr[trIdx].SelectNodes("td");
win?.Dispatcher?.Invoke(() => {
for (int tdIdx = 0; tdIdx < td.Count; tdIdx++)
{
var innerText = td[tdIdx].InnerText;
if (innerText.Contains("\n"))
{
innerText = innerText.Substring(0, innerText.IndexOf('\n'));
}
win.textBox.Text += innerText + "\t";
}
win.textBox.Text += "\n";
});
}
}
}
}
});
}
});
- 爬取網頁數據效果如下: