Python小爬虫——抓取豆瓣电影Top250数据

python抓取豆瓣电影Top250数据

1.豆瓣地址:https://movie.douban.com/top250?start=25&filter=

2.主要流程是抓取该网址下的Top250的数据,存入本地的txt文件中,并将数据持久化写入数据库中

环境准备:

1.本地安装mysql数据库,具体下载以及安装参照:https://blog.csdn.net/chic_data/article/details/72286329

2.安装好数据后创建database和table,并创建字段

如:我安装的版本是mysqlV8.0

CREATE TABLE doubanTop250(
ID int PRIMARY KEY AUTO_INCREMENT,
rankey int,
name varchar(50),
alias varchar(100),
director varchar(50),
showYear varchar(50),
makeCountry varchar(50),
movieType varchar(50),
movieScore float,
scoreNum int,
shortFilm varchar(255)
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

最后我们直接来看代码:

  

 from urllib import request
import re
import pymysql
class MovieTop(object):
def __init__(self):
self.start = 0
self.param = '&filter'
self.headers = {"User-Agent" : "Mozilla/5.0 (Windows NT 10.0; WOW64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/65.0.3325.146 Safari/537.36"}
self.movieList = []
self.filePath = './DoubanTop250.txt' def get_page(self):
try:
url = 'https://movie.douban.com/top250?start=' + str(self.start) + '&filter='
myRequest = request.Request(url, headers=self.headers)
response = request.urlopen(myRequest)
page = response.read().decode('utf-8')
print('正在获取第' + str((self.start+25)//25) + '页数据...')
self.start += 25
return page
except request.URLError as e:
if hasattr(e, 'reason'):
print('获取失败,失败原因:', e.reason) def get_page_info(self):
patern = re.compile(u'<div.*?class="item">.*?'
+ u'<div.*?class="pic">.*?'
+ u'<em.*?class="">(.*?)</em>.*?'
+ u'<div.*?class="info">.*?'
+ u'<span.*?class="title">(.*?)</span>.*?'
+ u'<span.*?class="other">(.*?)</span>.*?'
+ u'<div.*?class="bd">.*?'
+ u'<p.*?class="">.*?'
+ u'导演:\s(.*?)\s.*?<br>'
+ u'(.*?)&nbsp;/&nbsp;'
+ u'(.*?)&nbsp;/&nbsp;(.*?)</p>.*?'
+ u'<div.*?class="star">.*?'
+ u'<span.*?class="rating_num".*?property="v:average">'
+ u'(.*?)</span>.*?'
+ u'<span>(.*?)人评价</span>.*?'
+ u'<span.*?class="inq">(.*?)</span>'
, re.S) while self.start <= 225:
page = self.get_page()
movies = re.findall(patern, page)
for movie in movies:
self.movieList.append([movie[0],
movie[1],
movie[2].lstrip('&nbsp;/&nbsp;'),
movie[3],
movie[4].lstrip(),
movie[5],
movie[6].rstrip(),
movie[7],
movie[8],
movie[9]]) def write_page(self):
print('开始写入文件...')
file = open(self.filePath, 'w', encoding='utf-8')
try:
for movie in self.movieList:
file.write('电影排名:' + movie[0] + '\n')
file.write('电影名称:' + movie[1] + '\n')
file.write('电影别名:' + movie[2] + '\n')
file.write('导演:' + movie[3] + '\n')
file.write('上映年份:' + movie[4] + '\n')
file.write('制作国家/地区:' + movie[5] + '\n')
file.write('电影类别:' + movie[6] + '\n')
file.write('评分:' + movie[7] + '\n')
file.write('参评人数:' + movie[8] + '\n')
file.write('简短影评:' + movie[9] + '\n')
file.write('\n')
print('成功写入文件...')
except Exception as e:
print(e)
finally:
file.close() def upload(self):
db = pymysql.connect("localhost", "root", "root", "PythonTest", charset='utf8')
cursor = db.cursor() insertStr = "INSERT INTO doubanTop250(rankey, name, alias, director," \
"showYear, makeCountry, movieType, movieScore, scoreNum, shortFilm)" \
"VALUES (%d, '%s', '%s', '%s', '%s', '%s', '%s', %f, %d, '%s')" try:
for movie in self.movieList:
insertSQL = insertStr % (int(movie[0]), str(movie[1]), str(movie[2]), str(movie[3]),
str(movie[4]), str(movie[5]), str(movie[6]), float(movie[7]),
int(movie[8]), str(movie[9]))
cursor.execute(insertSQL)
db.commit()
print('成功上传至数据库...')
except Exception as e:
print(e)
db.rollback()
finally:
db.close() if __name__ == '__main__':
mt = MovieTop()
mt.get_page_info()
mt.write_page()
mt.upload()

执行结果:Python小爬虫——抓取豆瓣电影Top250数据

参照原文地址:https://www.cnblogs.com/AlvinZH/p/8576841.html#_label0

上一篇:为什么我刚发表的文章变成了“待审核”,csdn有没有官方解释啊


下一篇:python爬虫--爬取某网站电影信息并写入mysql数据库