記一次python 爬蟲爬取深圳租房信息的過程及遇到的問題
為了分析深圳市所有長租、短租公寓的信息,爬取了某租房公寓網(wǎng)站上深圳區(qū)域所有在租公寓信息,以下記錄了爬取過程以及爬取過程中遇到的問題:
爬取代碼:
import requestsfrom requests.exceptions import RequestExceptionfrom pyquery import PyQuery as pqfrom bs4 import BeautifulSoupimport pymongofrom config import *from multiprocessing import Poolclient = pymongo.MongoClient(MONGO_URL) # 申明連接對象db = client[MONGO_DB] # 申明數(shù)據(jù)庫def get_one_page_html(url): # 獲取網(wǎng)站每一頁的html headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' 'Chrome/85.0.4183.121 Safari/537.36' } try: response = requests.get(url, headers=headers) if response.status_code == 200: return response.text else: return None except RequestException: return Nonedef get_room_url(html): # 獲取當(dāng)前頁面上所有room_info的url doc = pq(html) room_urls = doc(’.r_lbx .r_lbx_cen .r_lbx_cena a’).items() return room_urlsdef parser_room_page(room_html): soup = BeautifulSoup(room_html, ’lxml’) title = soup.h1.text price = soup.find(’div’, {’class’: ’room-price-sale’}).text[:-3] x = soup.find_all(’div’, {’class’: ’room-list’}) area = x[0].text[7:-11] # 面積 bianhao = x[1].text[4:] house_type = x[2].text.strip()[3:7] # 戶型 floor = x[5].text[4:-2] # 樓層 location1 = x[6].find_all(’a’)[0].text # 分區(qū) location2 = x[6].find_all(’a’)[1].text location3 = x[6].find_all(’a’)[2].text subway = x[7].text[4:] addition = soup.find_all(’div’, {’class’: ’room-title’})[0].text yield { ’title’: title, ’price’: price, ’area’: area, ’bianhao’: bianhao, ’house_type’: house_type, ’floor’: floor, ’location1’: location1, ’location2’: location2, ’location3’: location3, ’subway’: subway, ’addition’: addition }def save_to_mongo(result): if db[MONGO_TABLE].insert_one(result): print(’存儲到mongodb成功’, result) return True return Falsedef main(page): url = ’http://www.xxxxx.com/room/sz?page=’ + str(page) # url就不粘啦,嘻嘻 html = get_one_page_html(url) room_urls = get_room_url(html) for room_url in room_urls: room_url_href = room_url.attr(’href’) room_html = get_one_page_html(room_url_href) if room_html is None: # 非常重要,否則room_html為None時(shí)會報(bào)錯(cuò) pass else: results = parser_room_page(room_html) for result in results:save_to_mongo(result)if __name__ == ’__main__’: pool = Pool() # 使用多進(jìn)程提高爬取效率 pool.map(main, [i for i in range(1, 258)])
在寫爬取代碼過程中遇到了兩個(gè)問題:
(一)在get_room_url(html)函數(shù)中,開始是想直接return每個(gè)租房信息的room_url,但是return不同于print,函數(shù)運(yùn)行到return時(shí)就會結(jié)束該函數(shù),這樣就只能返回每頁第一個(gè)租房room_url。解決辦法是:return 包含每頁所有room_url的generator生成器,在main函數(shù)中用for循環(huán)遍歷,再從每個(gè)room_url中獲取href,傳入到get_one_page_html(room_url_href)中進(jìn)行解析。
(二)沒有寫第76行的if語句,我默認(rèn)get_one_page_html(room_url_href)返回的room_html不為空,因此出現(xiàn)multiprocessing.pool.RemoteTraceback報(bào)錯(cuò):
上圖中顯示markup為None情況下報(bào)錯(cuò),點(diǎn)擊藍(lán)色'F:ProgramFilesanaconda3libsite-packagesbs4__init__.py'發(fā)現(xiàn)markup為room_html,即部分room_html出現(xiàn)None情況。要解決這個(gè)問題,必須讓代碼跳過room_html is None的情況,因此添加 if 語句解決了這個(gè)問題。
最終成功爬取某租房公寓深圳市258頁共4755條租房信息,為下一步進(jìn)行數(shù)據(jù)分析做準(zhǔn)備。
其中單條信息:
以上就是記一次python 爬蟲爬取深圳租房信息的過程及遇到的問題的詳細(xì)內(nèi)容,更多關(guān)于python 爬蟲的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. html中的form不提交(排除)某些input 原創(chuàng)2. ASP動態(tài)網(wǎng)頁制作技術(shù)經(jīng)驗(yàn)分享3. ASP常用日期格式化函數(shù) FormatDate()4. CSS3實(shí)現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效5. asp.net core項(xiàng)目授權(quán)流程詳解6. XMLHTTP資料7. vue使用moment如何將時(shí)間戳轉(zhuǎn)為標(biāo)準(zhǔn)日期時(shí)間格式8. CSS3中Transition屬性詳解以及示例分享9. jsp文件下載功能實(shí)現(xiàn)代碼10. 開發(fā)效率翻倍的Web API使用技巧
