python爬取豆瓣電影TOP250數(shù)據(jù)
在執(zhí)行程序前,先在MySQL中創(chuàng)建一個數(shù)據(jù)庫'pachong'。
import pymysqlimport requestsimport re#獲取資源并下載def resp(listURL): #連接數(shù)據(jù)庫 conn = pymysql.connect(host = ’127.0.0.1’,port = 3306,user = ’root’,password = ’******’, #數(shù)據(jù)庫密碼請根據(jù)自身實際密碼輸入database = ’pachong’, charset = ’utf8’ ) #創(chuàng)建數(shù)據(jù)庫游標(biāo) cursor = conn.cursor() #創(chuàng)建列表t_movieTOP250(執(zhí)行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:# 爬取數(shù)據(jù)for urlPath in listURL: # 獲取網(wǎng)頁源代碼 response = requests.get(urlPath) html = response.text # 正則表達(dá)式 namePat = r’alt='(.*?)' src=’ imgPat = r’src='https://www.xxx.com.cn/bcjs/(.*?)' class=’ # 匹配正則(排名【用數(shù)據(jù)庫中id代替,自動生成及排序】、電影名、電影海報(圖片地址)) res2 = re.compile(namePat) res3 = re.compile(imgPat) textList2 = res2.findall(html) textList3 = res3.findall(html) # 遍歷列表中元素,并將數(shù)據(jù)存入數(shù)據(jù)庫 for i in range(len(textList3)):cursor.execute(’insert into t_movieTOP250(movieName,pictrue_address) VALUES('%s','%s')’ % (textList2[i],textList3[i]))#從游標(biāo)中獲取結(jié)果cursor.fetchall()#提交結(jié)果conn.commit()print('結(jié)果已提交') except Exception as e:#數(shù)據(jù)回滾conn.rollback()print('數(shù)據(jù)已回滾') #關(guān)閉數(shù)據(jù)庫 conn.close()#top250所有網(wǎng)頁網(wǎng)址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)
結(jié)果如下圖:
以上就是我的分享,如果有什么不足之處請指出,多交流,謝謝!
以上就是python爬取豆瓣電影TOP250數(shù)據(jù)的詳細(xì)內(nèi)容,更多關(guān)于python爬取豆瓣電影的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. 讓chatgpt將html中的圖片轉(zhuǎn)為base64方法示例2. 用xslt+css讓RSS顯示的跟網(wǎng)頁一樣漂亮3. 《CSS3實戰(zhàn)》筆記--漸變設(shè)計(一)4. ASP.NET Core自定義中間件的方式詳解5. 移動端HTML5實現(xiàn)拍照功能的兩種方法6. CSS3實現(xiàn)動態(tài)翻牌效果 仿百度貼吧3D翻牌一次動畫特效7. 教你JS更簡單的獲取表單中數(shù)據(jù)(formdata)8. html5手機(jī)觸屏touch事件介紹9. ASP.NET MVC把數(shù)據(jù)庫中枚舉項的數(shù)字轉(zhuǎn)換成文字10. 測試模式 - XSL教程 - 5
