# Author:KRL
# -*- codeing = utf-8 -*-
# @Time :2021/7/3020:13
# @Author :MI
# @Site :
# @File :doubantop250.py
# @Software :PyCharm
# 拿到网页源代码 requests
# 利用re提取我们需要的内容 re
import requests
import re
import csv
url = "https://movie.douban.com/top250"
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36"
}
resp = requests.get(url,headers=headers)
page_content = resp.text
# print(resp.text)
# 解析数据
obj = re.compile(r'<li>.*? <div class="item">.*?<span class="title">(?P<name>.*?)</span>.*?'
r'<p class="">(?P<director>.*?); (?P<actors>.*?)<br>(?P<years>.*?)'
r' / (?P<country>.*?) / (?P<style>.*?)</p>.*?'
r'<span class="rating_num" property="v:average">(?P<score>.*?)</span>.*?'
r'<span>(?P<Number_of_comments>.*?)</span>.*?<span class="inq">(?P<motto>.*?)</span>',re.S)
# 开始匹配
result = obj.finditer(page_content)
# 写入CSV 为数据分析做准备
f = open("data.csv",mode="w",encoding='utf-8')
csvwriter = csv.writer(f)
for it in result:
# print(it.group("name"))
# print(it.group("director").strip())
# print(it.group("actors"))
# print(it.group("years").strip())
# print(it.group("country"))
# print(it.group("style").strip())
# print(it.group("score").strip())
# print(it.group("Number_of_comments"))
# print(it.group("motto"))
dic = it.groupdict()
dic['director'] = dic['director'].strip()
dic['years'] = dic['years'].strip()
dic['style'] = dic['style'].strip()
dic['score'] = dic['score'].strip()
csvwriter.writerow(dic.values())
f.close()
print('done!')