您的位置:首页 > 编程语言 > Python开发

Python 3.6 爬虫爬取豆瓣《孤芳不自赏》短评

2017-10-25 22:54 477 查看
使用Python 3.6 进行对《孤芳不自赏》这部作品的短评爬取

这部作品短评在豆瓣中的URL为:https://movie.douban.com/subject/26608228/comments?start=0&limit=20

点击这个连接我们可以进入该作品短评页面



这里还没有登录豆瓣。登录豆瓣之后,才能爬取更多的页面。

因此我们选择登录,最快捷省时的办法,就是在登录时使用F12进行查看cookies。

把cookies记下来,可以保持登录状态。



然后开始找需要的信息。

页面有很多信息,我们大概需要

短评用户的id、评分、日期、赞同数和内容等等。

建立一个类似这样的正则表达式进行匹配:

get_id = re.findall(r'<a.+people.+">(.+)</a>', html)
get_stars = re.findall(r'<span class="allstar(.+) rating" title=".+"></span>', html)
get_eval = re.findall(r'<span class=".+" title="(.+)"></span>', html)
get_comments = re.findall(r'<p class="">(.+)', html)
get_votes = re.findall(r'<span class="votes">(.+)</span>', html)
get_date = re.findall(r'201[0-9]-[0-9]+-[0-9]+', html, re.S)


然后开始写爬虫

# 《孤芳不自赏》,爬取豆瓣影评
import requests
import re
import pymysql
import time

def get_comment_info(html):
get_id = re.findall(r'<a.+people.+">(.+)</a>', html)
get_stars = re.findall(r'<span class="allstar(.+) rating" title=".+"></span>', html)
get_eval = re.findall(r'<span class=".+" title="(.+)"></span>', html)
get_comments = re.findall(r'<p class="">(.+)', html)
get_votes = re.findall(r'<span class="votes">(.+)</span>', html)
get_date = re.findall(r'201[0-9]-[0-9]+-[0-9]+', html, re.S)
n_page = re.findall(r'<a href="\?start=(\d+)&.+".+>', html)

db = pymysql.connect("localhost", "root", "5307", "douban_data", charset='utf8')
cursor = db.cursor()

if get_id:
for i in range(0, 19):
sql = """INSERT INTO movies_comments (id, stars, eval, comment_info, votes, date)
VALUES(%s,%s,%s,%s,%s,%s)"""
try:
cursor.execute(sql, (get_id[i], get_stars[i], get_eval[i], get_comments[i], get_votes[i], get_date[i]))
db.commit()
except Exception as e:
db.rollback()
continue
i += 1

db.close()
return n_page

if __name__ == '__main__':
# login douban.com
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'
}

cookies = {
'cookie': '使用你的cookies'
}

each = 25360
while 1:
url = 'https://movie.douban.com/subject/26608228/comments?start=' + str(
each) + '&limit=20&sort=new_score&status=P'
url_info = requests.get(url, cookies=cookies, headers=headers)
print("正在抓取评论,从第" + str(each) + "条开始")
next_page = get_comment_info(url_info.text)
time.sleep(10)
each = next_page[-1]


从MySQL中建立一个相关的表,进行数据的存储

最后运行爬虫,能获取到我们需要的信息



直观了解爬下来的数据

为了更好地了解爬下来的数据,以及了解这样的一部作品,需要对爬下来的数据进行粗略的分析。

短评获取到的数据是中文,可以对内容进行分词,查看每个词出现的频率。

用词云进行体现,可以知道这部作品的口碑:



这大概就达到了要求,得到了结果。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 豆瓣 爬虫