Python爬取豆瓣250,最新

import requests
from bs4 import BeautifulSoup

def get_movie_info(url):
    headers = {
        'User-Agent': 'Your User Agent Here',  # 使用你自己的User-Agent字符串
    }
    response = requests.get(url, headers=headers)
    if response.status_code == 200:
        soup = BeautifulSoup(response.text, 'html.parser')
        movie_list = soup.find_all('div', class_='item')
        movies = []
        for movie in movie_list:
            title = movie.find('span', class_='title').text.strip()  # 电影名称
            info_p = movie.find('div', class_='bd').find('p')
            country = ''
            year = ''
            genre = ''
            for child in info_p.children:
                if child.name == 'br':  # 如果遇到<br>标签,则在添加换行符后继续收集后续的文本
                    parts = ''.join(child.next_siblings).strip().split("/")
                    year = parts[0].strip()
                    country = parts[1].strip()
                    genre = parts[2].strip()
            movies.append({"title": title, "country": country, "year": year, "genre": genre})
        return movies


def main():
    base_url = 'https://movie.douban.com/top250'
    all_movies = []

    for i in range(10):
        print(f'开始抓取第{i + 1}页')
        url = f'{base_url}?start={(i * 25)}'
        movies = get_movie_info(url)
        for movie in movies:
            print(f'Title: {movie["title"]}')
            print(f'Country: {movie["year"]}')
            print(f'Year: {movie["country"]}')
            print(f'Genre: {movie["genre"]}\n')
        all_movies.extend(movies)
        print(f'抓取第{i + 1}页完成')

    print("抓取数据结果如下")
    #打印抓取的电影信息
    for movie in all_movies:
        print(f'Title: {movie["title"]}')
        print(f'Country: {movie["year"]}')
        print(f'Year: {movie["country"]}')
        print(f'Genre: {movie["genre"]}\n')


if __name__ == '__main__':
    main()

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值