1. 程式人生 > >簡易爬蟲:爬取豆瓣電影top250

簡易爬蟲:爬取豆瓣電影top250

爬蟲目的說明:

此爬蟲簡單到不能再簡單了,主要內容就是爬取豆瓣top250電影頁面的內容,然後將該內容匯入了資料庫。下面先上結果圖:

mysql_spider

爬蟲部分程式碼:

def getlist(listurl, result):
    time.sleep(2)
    headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.80 Safari/537.36'}
    res = requests.get(listurl, headers=headers)
    soup = BeautifulSoup(res.text, 'html.parser'
) movielist = soup.select('.grid_view li') for m in movielist: rank = m.select('em')[0].text if len(m.select('.title')) > 1: english_name = m.select('.title')[1].text.strip().strip('/').strip() else: english_name = "No info" chinese_name = m.select('.title'
)[0].text info_str = m.select('.info .bd p')[0].text.strip().replace(u'\xa0', u' ') info_list = info_str.split('\n') time_list = info_list[1].strip().split('/') movie_time = time_list[0].strip() movie_place = time_list[1].strip() movie_type = time_list[2].strip() director_list = info_list[0
].strip(u'導演:').split(' ') director = director_list[0].strip() if len(director_list) > 1: main_actor = director_list[1].strip().strip(u"主演:").strip() else: main_actor = u"暫無資訊" if m.select('.inq'): comments = m.select('.inq')[0].text.strip() else: comments = 'None' movie.append(u'排名: ' + rank + '\n' + u'電影名: ' + chinese_name + '\n' + u'導演: ' + director + '\n' + u'主演: ' + main_actor + '\n' + u'時間: ' + movie_time + '\n' + u'產地: '+ movie_place + '\n'+ u'型別: ' + movie_type + '\n' + u'評論: ' + comments + '\n') data_movies = (rank, chinese_name, english_name, director, main_actor, movie_time, movie_place, movie_type, comments) result.append(data_movies) #獲取下一頁 if soup.select(u'.next a'): asoup = soup.select(u'.next a')[0][u'href'] Next_page = lurl + asoup getlist(Next_page, result) else: print('Done') return result, movie

返回的resutl以及movie都是列表,result用來儲存儲存在資料庫中的內容,movie用來儲存寫入檔案中的內容。之所以分開儲存是因為,寫入檔案的每個元素都要加上諸如”導演“此類的說明詞彙,以便於理解;而資料庫已經有了列名,所以不需要這些說明詞彙。

資料庫匯入部分程式碼:

#連線資料庫
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="spider", use_unicode=True, charset="utf8")
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS MOVIE")
sql = """CREATE TABLE MOVIE (
         RANK INT(4),
         CHINESE_NAME CHAR(100),
         ENGLISH_NAME CHAR(100),
         DIRECTOR CHAR(100),
         MAIN_ACTORS CHAR(100),
         TIME CHAR(100),
         PLACE CHAR(100),
         TYPE CHAR(100),
         COMMENT CHAR(100) )"""
cursor.execute(sql)

lurl = 'https://movie.douban.com/top250'
movie = []
result = []
result, movies = getlist(lurl, result)
print(len(result))
#插入獲取的內容到資料庫
cursor.executemany(
        """
        INSERT INTO MOVIE (RANK, CHINESE_NAME, ENGLISH_NAME, DIRECTOR, MAIN_ACTORS, TIME, PLACE, TYPE, COMMENT) 
        VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)""",
        result
    )

db.commit()  #commit之後資料庫才會改動
cursor.close()
db.close()

Tips:

  1. 爬蟲部分:由於頁面顯示千差萬別,所以爬蟲部分程式碼最開始不要有對內容太細化的處理。
    太細化的處理會導致某些小問題的出現,以至於爬蟲不能正常進行。

  2. 資料庫匯入部分:資料庫匯入出現的錯誤大多就是編碼錯誤,所以注意這些就行了。