用selenium爬新浪部落格demo
阿新 • • 發佈:2018-11-06
經過一週的爬蟲學習,對python的爬蟲有了一些瞭解。寫一個小demo記錄一下學習成果。
匯入selenium包
from selenium import webdriver
# 捕獲異常,用於當部落格取完之後不報錯
from selenium.common.exceptions import NoSuchElementException
自動開啟谷歌瀏覽器
driver = webdriver.Chrome() # 自動啟動谷歌瀏覽器 main_window = driver.current_window_handle # 瀏覽器視窗 url = 'http://blog.sina.com.cn/s/articlelist_5698901077_0_1.html' # 部落格地址 driver.get(url)
對部落格進行解析
while True: boke_list = driver.find_elements_by_xpath('//div[@class = "articleCell SG_j_linedot1"]') # 爬取所有部落格放在list裡 print(boke_list) try: for boke in boke_list: # 迴圈遍歷每一篇部落格 title = boke.find_element_by_xpath('.//p/span/a').text # 用xpath找到每篇部落格題目並輸出 print(title) tag_a = boke.find_element_by_xpath('.//p/span/a') # 找到文章的詳情連結 tag_a.click() # click事件開啟詳情頁 boke_detail_window = driver.window_handles[-1] # 因為詳情頁,有兩個頁面,所以找到視窗的最後一個,也就是新開啟的那個 driver.switch_to.window(boke_detail_window) # 選中新開啟的頁面 content = driver.find_element_by_xpath('.//div[contains(@class, "articalContent")]').text # 獲取新開啟頁面裡邊的部落格內容 print(content) driver.close() # 關閉頁面 driver.switch_to.window(main_window) # 選擇主頁面,也就是最初的頁面 # blog = bytes(title+content) blog = '{title}.txt'.format(title=title) with open(blog,'w') as f: f.write(content) # 以文章標題為名儲存為txt文件 except NoSuchElementException as e: print('爬取完畢') break