記一次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): # 獲取當前頁面上所有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時會報錯 pass else: results = parser_room_page(room_html) for result in results:save_to_mongo(result)if __name__ == ’__main__’: pool = Pool() # 使用多進程提高爬取效率 pool.map(main, [i for i in range(1, 258)])
在寫爬取代碼過程中遇到了兩個問題:
(一)在get_room_url(html)函數(shù)中,開始是想直接return每個租房信息的room_url,但是return不同于print,函數(shù)運行到return時就會結(jié)束該函數(shù),這樣就只能返回每頁第一個租房room_url。解決辦法是:return 包含每頁所有room_url的generator生成器,在main函數(shù)中用for循環(huán)遍歷,再從每個room_url中獲取href,傳入到get_one_page_html(room_url_href)中進行解析。
(二)沒有寫第76行的if語句,我默認get_one_page_html(room_url_href)返回的room_html不為空,因此出現(xiàn)multiprocessing.pool.RemoteTraceback報錯:
上圖中顯示markup為None情況下報錯,點擊藍色'F:ProgramFilesanaconda3libsite-packagesbs4__init__.py'發(fā)現(xiàn)markup為room_html,即部分room_html出現(xiàn)None情況。要解決這個問題,必須讓代碼跳過room_html is None的情況,因此添加 if 語句解決了這個問題。
最終成功爬取某租房公寓深圳市258頁共4755條租房信息,為下一步進行數(shù)據(jù)分析做準備。
其中單條信息:
以上就是記一次python 爬蟲爬取深圳租房信息的過程及遇到的問題的詳細內(nèi)容,更多關(guān)于python 爬蟲的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 教你如何寫出可維護的JS代碼2. Vue的Options用法說明3. CSS可以做的幾個令你嘆為觀止的實例分享4. ASP刪除img標簽的style屬性只保留src的正則函數(shù)5. 使用Python和百度語音識別生成視頻字幕的實現(xiàn)6. 利用ajax+php實現(xiàn)商品價格計算7. xml中的空格之完全解說8. css代碼優(yōu)化的12個技巧9. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法10. 怎樣才能用js生成xmldom對象,并且在firefox中也實現(xiàn)xml數(shù)據(jù)島?
