場(chǎng)景:做為一個(gè)碼農,大部分都集中在一二線(xiàn)城市,所以租房也就無(wú)可避免,面對如今五花八門(mén)的租房信息,往往很難找到合適的房子。而如今的這些租房軟件,大部分也都被中介、廣告等給占據了。除了去中介公司,感覺(jué)再也找不到合適的房子,但是面對50%的中介費,很大程度上也難以忍受。偶然之間聽(tīng)朋友說(shuō)到可以去豆瓣看看,然后我就試著(zhù)去尋找一下,結果發(fā)現豆瓣討論組的信息太過(guò)雜亂,先不說(shuō)房源的好壞,光是找合適位置的帖子就得翻好久。。。
需求:所以,綜上場(chǎng)景所述,就寫(xiě)了個(gè)簡(jiǎn)單的爬蟲(chóng)來(lái)爬取需要的位置以及最新發(fā)布的一些房源帖子。這里實(shí)現比較簡(jiǎn)單,同樣豆瓣也有做一些防爬處理(IP訪(fǎng)問(wèn)次數等),而我并不是為了獲取更多的信息而爬取,只是為了方便。所以既沒(méi)有多線(xiàn)程處理,也沒(méi)有做反防爬。每次獲取的信息也足夠看了,不行的話(huà)就等第二天再看唄。
開(kāi)發(fā)環(huán)境:.NET Framework版本:4.5開(kāi)發(fā)工具:Visual Studio 2013實(shí)現代碼: private readonly string douBanUrl = "https://www.douban.com/group/search?cat=1019&sort=time";
bool isStop = false;
public FormCrawler() { InitializeComponent(); }
private void btn_start_Click(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txt_city.Text)) { MessageBox.Show("請輸入城市!"); return; } if (string.IsNullOrWhiteSpace(txt_keys.Text)) { MessageBox.Show("請輸入關(guān)鍵字!"); return; }
//初始化控件 btn_start.Enabled = false; btn_stop.Enabled = true; listView1.Items.Clear(); progressBar1.Value = 0;
List<string> groups = GetGroupUrls(); progressBar1.Maximum = groups.Count; Task.Run(() => { GetHouseInfo(groups);
this.BeginInvoke(new Action(() => { btn_start.Enabled = true; btn_stop.Enabled = false; })); });
}
private void btn_stop_Click(object sender, EventArgs e) { isStop = true; btn_start.Enabled = true; btn_stop.Enabled = false; progressBar1.Value = progressBar1.Maximum; }
private void listView1_MouseDoubleClick(object sender, MouseEventArgs e) { ListView.SelectedListViewItemCollection selectItem = listView1.SelectedItems; if (selectItem.Count > 0) { Process.Start(selectItem[0].SubItems[1].Text); } }
/// <summary> /// 獲取前100個(gè)討論組 /// </summary> /// <returns></returns> private List<string> GetGroupUrls() { List<string> groupUrls = new List<string>();
int pageSize = 20;//豆瓣每頁(yè)顯示20個(gè)討論組 string groupUrl = string.Empty;
for (int groupNum = 0; groupNum <= 80; groupNum += pageSize) { if (isStop) break;
groupUrl = string.Format(douBanUrl + "&q={0}&start={1}", HttpUtility.UrlEncode(txt_city.Text + "租房", Encoding.UTF8), groupNum);
string text = HttpUtil.HttpGet(groupUrl);
if (!string.IsNullOrWhiteSpace(text)) { Regex reg = new Regex(@"(?is)(?<=<div\sclass=""pic""[^>]*?>).*?(?=</div>)"); MatchCollection matchs = reg.Matches(text); for (int i = 0; i < matchs.Count; i++) { if (matchs[i].Success) { Regex regHref = new Regex("(?<=href\\s*=\\s*\")\\S+(?<!\")"); string href = regHref.Match(matchs[i].Value).Value; groupUrls.Add(href); } } } }
return groupUrls; }
/// <summary> /// 獲取討論組內符合條件的房源 /// </summary> /// <param name="urls"></param> private void GetHouseInfo(List<string> urls) { for (int u = 0; u < urls.Count; u++) { if (isStop) break; this.BeginInvoke(new Action(() => { progressBar1.Value++; }));
string text = HttpUtil.HttpGet(urls[u] + "/discussion?start="); Regex regex = new Regex(@"(?is)(?<=<tr\sclass=""""[^>]*?>).*?(?=</tr>)"); MatchCollection matchs = regex.Matches(text); for (int i = 0; i < matchs.Count; i++) { if (matchs[i].Success) { #region 匹配時(shí)間 Regex regDate = new Regex(@"(?is)(?<=<td\snowrap=""nowrap""\sclass=""time""[^>]*?>).*?(?=</td>)"); Match matchDate = regDate.Match(matchs[i].Value); if (!matchDate.Success) { continue; } string time = matchDate.Value; DateTime dtTemp = new DateTime(); if (!DateTime.TryParse(time, out dtTemp)) { time = time.Insert(0, DateTime.Now.Year + "-"); dtTemp = Convert.ToDateTime(time); } if (dtTemp < dateTimePicker1.Value.Date) { continue; } #endregion
#region 獲取標題
Regex regTitle = new Regex("(?<=title\\s*=\\s*\")\\s*\\S*(?<!\")"); Match matchTitle = regTitle.Match(matchs[i].Value); if (matchTitle.Success) { string title = matchTitle.Value; #region 匹配標題 bool isContain = false; string[] keys = txt_keys.Text.Split('*'); foreach (string key in keys) { if (matchTitle.Value.Contains(key)) { isContain = true; } } #endregion if (isContain) { //獲取鏈接 Regex regHref = new Regex("(?<=href\\s*=\\s*\")\\s*\\S*(?<!\")"); string href = regHref.Match(matchs[i].Value).Value;
AddUI(title, href, time); } } #endregion }
} } }
private void AddUI(string title, string href, string time) { if (this.InvokeRequired) { this.BeginInvoke(new Action(() => AddUI(title, href, time))); } else { ListViewItem lvitem = new ListViewItem(new string[3] { title, href, time }); listView1.Items.Add(lvitem); } }
實(shí)現效果:
代碼解析:主要是使用了HttpGet來(lái)獲取鏈接的網(wǎng)頁(yè)信息,然后使用正則匹配我們的需求數據。每次只訪(fǎng)問(wèn)100個(gè)討論組,每個(gè)討論組內獲取第一頁(yè)的帖子信息。如果不使用代理ip或者其他反防爬機制的話(huà),基本上這個(gè)軟件每天只使用一次就達到上限了(獲取到的數據為空等);要是沒(méi)有合適的帖子的話(huà),可以第二天再查找一下。
本代碼只用于學(xué)習交流,請勿用于非法用途。
由簡(jiǎn)入繁,拿來(lái)即用
本站僅提供存儲服務(wù),所有內容均由用戶(hù)發(fā)布,如發(fā)現有害或侵權內容,請
點(diǎn)擊舉報。