Python爬蟲之豆瓣電影TOP250
話不多說先上代碼:
`import requests
import bs4
import os
import string
import mysql.connector
def getHTMLText(url):
print(url)
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding =“utf-8”
return r.text
except:
return""
def fillUnlivList(soup):
datas=soup.find_all(“div”,{“class”:“item”})
for data in datas:
name=data.find(“span”,{“class”:“title”})
name=nme.string
name=str(name)
score=data.find(“span”,{“class”:“rating_num”})
score=a.string
score=str(score)
introduction=data.find(“span”,{“class”:“inq”})
introduction=idea.string
introduction=str(idea)
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="runoob_db")
mycursor=mydb.cursor()
sql = "INSERT INTO sites (name, score, introduction) VALUES (%s, %s,%s)"
val=(name,score,introduction)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, "記錄插入成功。")
def main():
url=“https://movie.douban.com/top250?start=”
print(“正在爬取豆瓣電影TOP250”)
for i in range(0,9):
n=i*25
print(“第”+str(i+1)+“頁”)
url_i=url+str(n)+"&filter="
html=getHTMLText(url_i)
soup=bs4.BeautifulSoup(html, “html.parser”)
fillUnlivList(soup)
print(“爬取完成”)
main()
`首先我們需要先把幾個需要的包導入。這裡就不寫怎麼導了。
第一步我們先定義擷取網頁代碼的函數
def getHTMLText(url):
print(url)
try:
r=requests.get(url,timeout=30)
r.raise_for_status()#擷取失敗時報錯
r.encoding =“utf-8”#設定編碼格式是UTF-8
return r.text
except:
return""
目标網頁:https://movie.douban.com/top250?start=
這是第一頁的網址

這是第二頁的網址
根據我們的觀察可以發現第一頁與第二頁的網址隻有start=後面的不同,再根據我們的統計,第一頁有25部電影推薦。是以我們可以得出結論:我們需要爬取下一頁的内容時我們隻需要改變start=後面的數值。
是以我們的分頁代碼部分就可以寫出
開始擷取自己想要的内容:每一部電影都在一個li
電影名字在一個span
因為我們隻要第一個是以隻用find找到第一個
評分和介紹與名字差不多
datas=soup.find_all(“div”,{“class”:“item”})#找到所有電影的DIV
for data in datas:
name=data.find(“span”,{“class”:“title”})#找到名字的SPAN
name=nme.string
name=str(name)#因為我們擷取的name不是String類型,而存入MYSQL必須是String是以需要轉換
score=data.find(“span”,{“class”:“rating_num”})
score=a.string
score=str(score)
introduction=data.find(“span”,{“class”:“inq”})
introduction=idea.string
introduction=str(idea)
接下來開始存入資料庫:
1.建立資料庫,建立表,
字元集一定要是utf8。
2.連接配接資料庫
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",#;我沒有密碼是以沒寫
database="runoob_db")#資料庫名字
3.插入資料
mycursor=mydb.cursor()
sql = “INSERT INTO sites (name, score, introduction) VALUES (%s, %s,%s)”
val=(name,score,introduction)
mycursor.execute(sql, val)
mydb.commit()
print(mycursor.rowcount, “記錄插入成功。”)
完成後的效果: