爬蟲實戰----簡書的爬取和儲存
阿新 • • 發佈:2018-11-30
網站:
網站資料結構分析:
滑輪拉到最下面:
這是一個懶載入,只有點選閱讀更多的時候,才會有後續的資料,我們可以使用selenium。
並且可以設定點選的次數,程式碼如下:
browser = webdriver.Chrome() browser.get('https://www.jianshu.com/') for i in range(3): # 將滑輪滑到底部 browser.execute_script("window.scrollTo(0, document.body.scrollHeight);") time.sleep(2) for i in range(5): # 嘗試點選閱讀更多的按鈕 try: button = browser.find_element_by_class_name('load-more') button.click() time.sleep(2) except Exception as e: pass
提取資料:
需要的資料都在a標籤中,提取資料程式碼如下:
titles = browser.find_elements_by_class_name('title')
儲存資料:
def db(titles): print(titles) db = pymysql.connect(host = 'localhost',user = 'root',password='123456',port=3306,db='images360',charset='utf8') cursor = db.cursor() for info in titles: # print(info) sql = "insert into jianshu values('%s','%s')" % (info.text,info.get_attribute('href')) try: cursor.execute(sql) print('Successful') db.commit() except Exception as e: print('Failed',e) cursor.close() db.close()
資料庫和表都是自己建立的。執行之後就可以獲得自己想要的結果了。
建立資料庫程式碼如下:
CREATE DATABASE images360
建立表的程式碼如下:
CREATE TABLE jianshu
(
title VARCHAR(255),
href VARCHAR(255)
)