爬取網(wǎng)址:https://movie.douban.com/top250
爬取信息:電影名稱,導(dǎo)演,主演,類型,制片國家,上映時間,片長,評分
爬取方式:進(jìn)入詳細(xì)頁面爬取,lxml,re解析。
存儲方式:MySQL存儲

image.png
使用MySQL存儲,首先需要在SQLyog中建立數(shù)據(jù)表:
CREATE TABLE topmovies (
電影名稱 TEXT,
導(dǎo)演 TEXT,
主演 TEXT,
類型 TEXT,
制片地 TEXT,
上映時間 TEXT,
片長 TEXT,
評分 TEXT
)ENGINE INNODB DEFAULT CHARSET=utf8;
注意:中文字段無需用""括起來,不能寫成:"電影名稱" TEXT。
然后在快捷菜單中選擇“執(zhí)行查詢”或使用F9鍵執(zhí)行代碼,即可完成數(shù)據(jù)表的創(chuàng)建。

image.png
代碼如下:
import requests
from lxml import etree
import re
import pymysql
import time
def get_details_url(url):
r = requests.get(url,headers = headers)
html = etree.HTML(r.text)
movie_urls = html.xpath('//div[@class="pic"]/a/@href')
return movie_urls
def get_info(url):
r = requests.get(url,headers=headers)
html = etree.HTML(r.text)
try:
name = html.xpath('//div[@id="content"]/h1/span[1]/text()')[0]
director = html.xpath('//div[@id="info"]/span[1]/span[2]/a/text()')[0]
actor1 = html.xpath('//div[@id="info"]/span[3]/span[2]')[0]
actor = actor1.xpath('string(.)')
style1 = re.findall('<span property="v:genre">(.*?)</span>',r.text,re.S) ##若采用xpath的標(biāo)簽定位,有可能發(fā)生爬取數(shù)據(jù)錯位。
style = '/'.join(style1)
country = re.findall('制片國家/地區(qū):</span>(.*?)<br/>',r.text,re.S)[0].strip()
release_time1 = re.findall('<span property="v:initialReleaseDate" content="(.*?)">',r.text,re.S)
release_time = '/'.join(release_time1)
run_time = re.findall('片長:</span> <span.*?>(.*?)</span>',r.text,re.S)[0]
score = re.findall('property="v:average">(.*?)</strong>',r.text,re.S)[0]
#print(name,director,actor,style,country,release_time,run_time,score)
cursor.execute('INSERT INTO topmovies(電影名稱,導(dǎo)演,主演,類型,制片地,上映時間,片長,評分) VALUES (%s,%s,%s,%s,%s,%s,%s,%s)',
(name,director,actor,style,country,release_time,run_time,score))
except IndexError:
pass ##忽略IndexError,因為有些影片的詳細(xì)頁面沒內(nèi)容。
if __name__ == "__main__":
conn = pymysql.connect(host='localhost',user='root',db='mydb',port=3306,charset="utf8") #連接數(shù)據(jù)庫
cursor = conn.cursor() #光標(biāo)對象
headers = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3294.6 Safari/537.36'}
url_list = ['https://movie.douban.com/top250?start={}&filter='.format(i*25) for i in range(0,10)] #共10頁
for url in url_list:
movie_urls = get_details_url(url)
for movie_url in movie_urls:
get_info(movie_url)
time.sleep(2)
conn.commit() #提交事務(wù)
結(jié)果為:

image.png
可以看到,總共獲取了245個數(shù)據(jù)。如果要獲得完整數(shù)據(jù),也可以考慮把概述頁的內(nèi)容提取出來,即遇到Indexerror后提取電影的概述數(shù)據(jù)。
數(shù)據(jù)庫中的信息樣式為:

image.png