如何高效地爬取链家的房源信息(三)
“Python實現的鏈家網站的爬蟲第三部分。”
本系列文將以鏈家南京站為例,使用Python實現鏈家二手房源信息的爬蟲,將數據爬取,并存入數據庫中,以便使用。
本系列第一部分為基礎:
如何高效地爬取鏈家的房源信息(一)
本系列第二部分為爬取小區信息:
如何高效地爬取鏈家的房源信息(二)
本文是第三部分,爬取在售二手房信息并存入數據庫,部分代碼依賴于第一部分,同時依賴于第二部分的結果。
在前文中已經獲取了小區信息,并存在了數據庫中,直接讀庫遍歷小區進行爬取:
def do_xiaoqu_zaishou_spider(db_xq,db_zs):
? ? """
? ? 批量爬取小區在售
? ? """
? ? count=0
? ? xq_list=db_xq.fetchall()
? ? for xq in xq_list:
? ? ? ? xiaoqu_zaishou_spider(db_cj,xq[0])
? ? ? ? count+=1
? ? ? ? print ('have spidered zaishou %d xiaoqu %s' % (count,xq[0]))
? ? print( 'done')
對某一個小區內的所有在售房源進行爬取,需要分頁:
def xiaoqu_zaishou_spider(db_cj, xq_url=u"https://nj.lianjia.com/xiaoqu/1411000000391/"):
? ? """
? ? 爬取小區在售
? ? """
? ? url = xq_url.replace('xiaoqu/','ershoufang/c');
? ? try:
? ? ? ? req = urllib.request.Request(url, headers=hds[random.randint(0, len(hds) - 1)])
? ? ? ? source_code = urllib.request.urlopen(req, timeout=10).read()
? ? ? ? plain_text = source_code.decode('utf-8')
? ? ? ? soup = BeautifulSoup(plain_text,"html.parser")
? ? except (urllib.request.HTTPError, urllib.request.URLError) as e:
? ? ? ? print(e)
? ? ? ? exception_write('xiaoqu_zaishou_spider', xq_url)
? ? ? ? return
? ? except Exception as e:
? ? ? ? print(e)
? ? ? ? exception_write('xiaoqu_zaishou_spider', xq_url)
? ? ? ? return
? ? content = soup.find('div', {'class': 'page-box house-lst-page-box'})
? ? total_pages = 0
? ? if content:
? ? ? ? d = "d=" + content.get('page-data')
? ? ? ? loc = {}
? ? ? ? glb = {}
? ? ? ? exec(d, glb, loc);
? ? ? ? total_pages = loc['d']['totalPage']
? ? threads = []
? ? for i in range(total_pages):
? ? ? ? tmp= u'ershoufang/pg%dc'% (i + 1)
? ? ? ? url_page = url.replace('ershoufang/c',tmp);
? ? ? ? t = threading.Thread(target=zaishou_spider, args=(db_cj, url_page))
? ? ? ? threads.append(t)
? ? for t in threads:
? ? ? ? t.start()
? ? for t in threads:
? ? ? ? t.join()
爬取單個頁面內的在售信息:
def zaishou_spider(db_cj, url_page=u"https://nj.lianjia.com/chengjiao/pg4c1411000000142/"):
? ? """
? ? 爬取頁面鏈接中的在售
? ? """
? ? try:
? ? ? ? req = urllib.request.Request(url_page, headers=hds[random.randint(0, len(hds) - 1)])
? ? ? ? source_code = urllib.request.urlopen(req, timeout=10).read()
? ? ? ? plain_text = source_code.decode('utf-8');
? ? ? ? soup = BeautifulSoup(plain_text,"html.parser")
? ? except (urllib.request.HTTPError, urllib.request.URLError) as e:
? ? ? ? print(e)
? ? ? ? exception_write('zaishou_spider', url_page)
? ? ? ? return
? ? except Exception as e:
? ? ? ? print(e)
? ? ? ? exception_write('zaishou_spider', url_page)
? ? ? ? return
? ? cjs = soup.find('ul', {'class': 'sellListContent'});
? ? cj_list = cjs.findAll('li', {})
? ? for cj in cj_list:
? ? ? ? info_dict = {}
? ? ? ? title = cj.find('div', {'class': 'title'});
? ? ? ? houseInfo = cj.find('div', {'class': 'houseInfo'});
? ? ? ? positionInfo = cj.find('div', {'class': 'positionInfo'});
? ? ? ? followInfo = cj.find('div', {'class': 'followInfo'});
? ? ? ? tag = cj.find('div', {'class': 'tag'});
? ? ? ? totalPrice = cj.find('div', {'class': 'totalPrice'});
? ? ? ? unitPrice = cj.find('div', {'class': 'unitPrice'});
? ? ? ? href = title.find('a')
? ? ? ? if not href:
? ? ? ? ? ? continue
? ? ? ? info_dict.update({u'鏈接': href.attrs['href']})
? ? ? ? content = title.text
? ? ? ? info_dict.update({u'房子描述': content})
? ? ? ? content = houseInfo.text.split('|')??
#有可能有別墅項,有可能無部分項
? ? ? ? if content:
? ? ? ? ? ? info_dict.update({u'小區名稱': content[0].strip()})
? ? ? ? ? ? if content[1].find(u'墅') != -1:
? ? ? ? ? ? ? ? i=1;
? ? ? ? ? ? else:
? ? ? ? ? ? ? ? i=0;
? ? ? ? ? ? if len(content) >= 2+i:
? ? ? ? ? ? ? ? info_dict.update({u'戶型': content[1+i].strip()})
? ? ? ? ? ? if len(content) >= 3+i:
? ? ? ? ? ? ? ? info_dict.update({u'面積': content[2+i].strip()})
? ? ? ? ? ? if len(content) >= 4+i:
? ? ? ? ? ? ? ? info_dict.update({u'朝向': content[3+i].strip()})
? ? ? ? ? ? if len(content) >= 5+i:
? ? ? ? ? ? ? ? info_dict.update({u'裝修': content[4+i].strip()})
? ? ? ? ? ? if len(content) >= 6+i:
? ? ? ? ? ? ? ? info_dict.update({u'電梯': content[5+i].strip()})
? ? ? ? content = positionInfo.text.split('-')
? ? ? ? if len(content) >= 2:
? ? ? ? ? ? info_dict.update({u'樓層年代樓型': content[0].strip()})?
? ? ? ? ? ? info_dict.update({u'區域': content[1].strip()})??
? ? ? ? else:
? ? ? ? ? ? info_dict.update({u'區域': content[0].strip()})??
? ? ? ? content = followInfo.text.split('/')
? ? ? ? for cont in content:
? ? ? ? ? ? if cont.find(u'關注') != -1:
? ? ? ? ? ? ? ? info_dict.update({u'關注': cont.strip()})
? ? ? ? ? ? elif cont.find(u'帶看') != -1:
? ? ? ? ? ? ? ? info_dict.update({u'帶看': cont.strip()})
? ? ? ? ? ? elif cont.find(u'發布') != -1:
? ? ? ? ? ? ? ? info_dict.update({u'發布時間': cont.strip()})
? ? ? ? if tag != None:
? ? ? ? ? ? tagall=tag.findAll('span')
? ? ? ? ? ? for span in tagall:
? ? ? ? ? ? ? ? if span.attrs['class'][0] ==u'taxfree':
? ? ? ? ? ? ? ? ? ? info_dict.update({u'稅費': span.text})? # 滿幾年
? ? ? ? ? ? ? ? elif span.attrs['class'][0] ==u'subway':
? ? ? ? ? ? ? ? ? ? info_dict.update({u'地鐵': span.text})
? ? ? ? ? ? ? ? elif span.attrs['class'][0] ==u'haskey':
? ? ? ? ? ? ? ? ? ? info_dict.update({u'限制': span.text})
? ? ? ? info_dict.update({u'掛牌價': totalPrice.text})
? ? ? ? info_dict.update({u'掛牌單價': unitPrice.text})
? ? ? ? command = gen_zaishou_insert_command(info_dict)
? ? ? ? db_zs.execute(command, 1)
爬取的在售房源信息將被存儲到數據庫表中。
在接下來將說明如何爬取歷史成交二手房信息,敬請期待。
長按進行關注。
總結
以上是生活随笔為你收集整理的如何高效地爬取链家的房源信息(三)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 如何高效地爬取链家的房源信息(二)
- 下一篇: 如何高效地爬取链家的房源信息(四)