1. 程式人生 > >資料抓取必須學會的三種技術

資料抓取必須學會的三種技術

我們正處於一個大資料的時代,在這樣的一個以資料為王的時代,第一步就是如何獲取資料。大概的流程是這樣的:通過Http客戶端獲取html頁面,通過html頁面解析工具解析html頁面,獲取感興趣的資料元素,最後將解析後的資料寫入資料庫。Python為這幾個過程都提供了很方便的庫供我們呼叫,使得資料獲取簡單快捷。

HTTP客戶端

Requests,這裡是它的主頁
這樣一條語句就能獲取到html頁面了

html = requests.get(url, headers=headers).text 

HTML頁面解析器

Beautiful Soup,這裡是它的主頁
這樣一條語句就解析好html頁面了

soup = BeautifulSoup(html,"html.parser")

MySQL資料庫客戶端

PyMySQL,這裡是它的主頁,都不需要Mysql的驅動庫,直接安裝使用。

    con = pymysql.connect(host='localhost',
                             user='root',
                             password='root',
                             db='test',
                             charset='utf8mb4'
, cursorclass=pymysql.cursors.DictCursor) try: with con.cursor() as cursor: sql = "insert into tbl_movie (title, director, director_factor, actors, actors_factor, year, country, types, rating) values(%s,%s,%s,%s,%s,%s,%s,%s,%s)" cursor.execute(sql, (title, director,director_factor,actors,actors_factor,year,country,types,rating)) con.commit() finally
: con.close()