python爬取豆瓣電影TOP250數(shù)據(jù)
發(fā)布日期:2022-04-15 16:53 | 文章來源:CSDN
在執(zhí)行程序前,先在MySQL中創(chuàng)建一個數(shù)據(jù)庫"pachong"。
import pymysql
import requests
import 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ù)庫游標
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
# 正則表達式
namePat = r'alt="(.*?)" src='
imgPat = r'src="(.*?)" 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]))
#從游標中獲取結(jié)果
cursor.fetchall()
#提交結(jié)果
conn.commit()
print("結(jié)果已提交")
except Exception as e:
#數(shù)據(jù)回滾
conn.rollback()
print("數(shù)據(jù)已回滾")
#關閉數(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+pagePat
urlList.append(urL)
return urlList
if __name__ == '__main__':
url = r"https://movie.douban.com/top250"
listURL = page(url)
resp(listURL)
結(jié)果如下圖:


以上就是我的分享,如果有什么不足之處請指出,多交流,謝謝!
以上就是python爬取豆瓣電影TOP250數(shù)據(jù)的詳細內(nèi)容,更多關于python爬取豆瓣電影的資料請關注本站其它相關文章!
版權聲明:本站文章來源標注為YINGSOO的內(nèi)容版權均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復制或仿造本網(wǎng)站,禁止在非maisonbaluchon.cn所屬的服務器上建立鏡像,否則將依法追究法律責任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學習參考,不代表本站立場,如有內(nèi)容涉嫌侵權,請聯(lián)系alex-e#qq.com處理。
相關文章
下一篇:
關注官方微信