1. 程式人生 > >利用selenium爬取攜程酒店資訊

利用selenium爬取攜程酒店資訊

上節部落格我們利用requests請求庫,正則表示式來提取資訊(連結https://mp.csdn.net/postedit/81865681),提到過使用selenium也可以抓取酒店資訊,在這裡利用selenium模組優點是不需要資料處理過濾,只需要處理異常,(實際上也是一樣的效果)但是對於使用selenium爬取效率太慢。

具體的分析如上節分析的類似,只是定位元素是利用find_element(s)_by_id,find_element(s)_by_class_name等等定位方法。下面直接給出程式碼。如有疑問,可留言一起探討。

import time
from selenium  import webdriver
from selenium.webdriver.common.keys import Keys   
from selenium.common.exceptions import NoSuchElementException  ###匯入異常屬性
from pymongo import MongoClient
driver=webdriver.Chrome()
url='http://hotels.ctrip.com/hotel/nanjing12#ctm_ref=ctr_hp_sb_lst'
driver.get(url)
time.sleep(2)
button=driver.find_element_by_css_selector('#appd_wrap_close')
button.click()
page=driver.find_element_by_css_selector('#page_info > div.c_page_list.layoutfix > a:nth-child(9)')  ###定位總頁數
for m in range(int(page.text)) :
    if m :
        next_button=driver.find_element_by_css_selector('.c_down')       
        next_button.send_keys(Keys.ENTER)
    driver.execute_script('window.scrollBy(0,5800)')
    time.sleep(2)    
    infor=driver.find_element_by_css_selector('#hotel_list').find_elements_by_class_name('hotel_new_list')
   # print(len(infor))
    for data in infor :
        try:
            hotel_level=data.find_element_by_css_selector('ul > li.hotel_item_judge.no_comment > div.hotelitem_judge_box > a > span.hotel_level').text
        except NoSuchElementException :
            hotel_level=''
        try:
            recommend=data.find_element_by_css_selector(' ul > li.hotel_item_judge.no_comment > div.hotelitem_judge_box > a > span.recommend').text
        except NoSuchElementException :
            recommend=' '
            
        hotel_information= {
        'title':data.find_element_by_css_selector(' ul > li.pic_medal > div > a').get_attribute('title'),
        
        'adress':data.find_element_by_css_selector(' ul > li.hotel_item_name > p.hotel_item_htladdress').text.rstrip('地圖'and'地圖街景') ,
        
        'hotle_score':hotel_level+data.find_element_by_css_selector('ul > li.hotel_item_judge.no_comment > div.hotelitem_judge_box > a > span.hotel_value').text,
    
        'lowestprice':data.find_element_by_css_selector('ul > li.hotel_price_icon > div > div > div > a > span').text,

        'recommend':recommend,

        }
        print(hotel_information)
        client=MongoClient()
        db=client['ctrip']
        collection=db['hotels information']
        collection.insert_one(hotel_information)
        
    

執行得到部分結果截圖如下:

原創不易,如若轉載,請註明出處與作者,謝謝!