python爬取豆瓣電影TOP250數據
在執行程序前,先在MySQL中創建一個數據庫'pachong'。
import pymysqlimport requestsimport re#獲取資源并下載def resp(listURL): #連接數據庫 conn = pymysql.connect(host = ’127.0.0.1’,port = 3306,user = ’root’,password = ’******’, #數據庫密碼請根據自身實際密碼輸入database = ’pachong’, charset = ’utf8’ ) #創建數據庫游標 cursor = conn.cursor() #創建列表t_movieTOP250(執行sql語句) cursor.execute(’create table t_movieTOP250(id INT PRIMARY KEY auto_increment NOT NULL ,movieName VARCHAR(20) NOT NULL ,pictrue_address VARCHAR(100))’) try:# 爬取數據for urlPath in listURL: # 獲取網頁源代碼 response = requests.get(urlPath) html = response.text # 正則表達式 namePat = r’alt='(.*?)' src=’ imgPat = r’src='https://www.xxx.com.cn/bcjs/(.*?)' class=’ # 匹配正則(排名【用數據庫中id代替,自動生成及排序】、電影名、電影海報(圖片地址)) res2 = re.compile(namePat) res3 = re.compile(imgPat) textList2 = res2.findall(html) textList3 = res3.findall(html) # 遍歷列表中元素,并將數據存入數據庫 for i in range(len(textList3)):cursor.execute(’insert into t_movieTOP250(movieName,pictrue_address) VALUES('%s','%s')’ % (textList2[i],textList3[i]))#從游標中獲取結果cursor.fetchall()#提交結果conn.commit()print('結果已提交') except Exception as e:#數據回滾conn.rollback()print('數據已回滾') #關閉數據庫 conn.close()#top250所有網頁網址def page(url): urlList = [] for i in range(10):num = str(25*i)pagePat = r’?start=’ + num + ’&filter=’urL = url+pagePaturlList.append(urL) return urlListif __name__ == ’__main__’: url = r'https://movie.douban.com/top250' listURL = page(url) resp(listURL)
結果如下圖:
以上就是我的分享,如果有什么不足之處請指出,多交流,謝謝!
以上就是python爬取豆瓣電影TOP250數據的詳細內容,更多關于python爬取豆瓣電影的資料請關注好吧啦網其它相關文章!
相關文章: