Python爬取豆瓣电影Top250数据

任务

爬取豆瓣电影top250中的影片名称、影片海报、年份、地区、类型、评分、评价人数、总体评价,并输出到douban_top250.xlsx文件中

环境

Python 3.8

requests

bs4

openpyxl

源码

python 复制代码
# 创建一个新的Excel工作簿
workbook = openpyxl.Workbook()
# 获取默认的工作表
sheet = workbook.active
# 写入数据
sheet['A1'] = '序号'
sheet['B1'] = '电影名'
sheet['C1'] = '海报'
sheet['D1'] = '年份'
sheet['E1'] = '地区'
sheet['F1'] = '类型'
sheet['G1'] = '评分'
sheet['H1'] = '评价人数'
sheet['I1'] = '总体评价'
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36"
}
index = 1
for start_page in range(0, 250, 25):
    response = requests.get(f"https://movie.douban.com/top250?start={start_page}", headers=headers)
    html = response.text
    # html.parser表示使用html进行解析
    soup = BeautifulSoup(html, "html.parser")
    items = soup.find_all("div", attrs={"class": "item"})
    for item in items:
        # 海报
        post = item.find("img").get('src')
        # 名称
        name = item.find('span', class_="title").text
        # 年份
        infos = item.find('p', class_='').text.split("\n")[2].split("/")
        year = infos[0].strip()
        location = infos[1].strip()
        category = infos[2].strip()
        rate = item.find('span', class_='rating_num').text
        stars = item.find('div', class_='star')
        rate_people = stars.contents[7].text[:-3]
        review = ""
        if item.find('span', class_='inq') is not None:
            review = item.find('span', class_='inq').text
        sheet.append([index, name, post, year, location, category, rate, rate_people, review])
        index = index + 1
# 保存工作簿
workbook.save('./files/douban_top250.xlsx')

结果

相关推荐
张子夜 iiii3 小时前
(0️⃣基础)程序控制语句(初学者)(第3天)
人工智能·python
码农派大星。6 小时前
Selenium在Pyhton应用
python·selenium·测试工具
day>day>up7 小时前
django uwsgi启动报错failed to get the Python codec of the filesystem encoding
后端·python·django
Shun_Tianyou7 小时前
Python Day25 进程与网络编程
开发语言·网络·数据结构·python·算法
都叫我大帅哥8 小时前
LangGraph条件判断:让AI工作流"聪明"起来
python·langchain
编程研究坊9 小时前
Neo4j APOC插件安装教程
数据库·人工智能·python·neo4j
咩?9 小时前
SEABORN库函数(第十八节课内容总结)
开发语言·python·matplotlib·seaborn
万粉变现经纪人9 小时前
如何解决pip安装报错ModuleNotFoundError: No module named ‘transformers’问题
人工智能·python·beautifulsoup·pandas·scikit-learn·pip·ipython
浊酒南街9 小时前
Pytorch基础入门1
pytorch·python
仪器科学与传感技术博士10 小时前
Matplotlib库:Python数据可视化的基石,发现它的美
开发语言·人工智能·python·算法·信息可视化·matplotlib·图表可视化