Python 爬虫实战:自动获取豆瓣电影 TOP250 排行榜信息及评论
{
'title': '使用Python编写爬虫,自动爬取豆瓣电影TOP250排行榜中250部影片并利用BeautifulSoup4库提取相关信息,包含基本信息('排名','海报','片名','评分','导演','主演','上映时间','上映地点','类型','热门短评')与第一页前10名影片的前5条热门短评(如果是5条短评,请加上序号并用换行分隔,如1.这是一部好电影等)(注意:'海报'列存储的是获取海报图片并保存在本地之后对本地图片文件的超链接,'片名'列存储的是影片的名字并超链接到影片详情页,超链接的添加请自行搜索相关资料,'热门短评'列如果不是前10影片,只需要存储列表页上显示的那一条热门评论即可),利用pandas库打印出信息,并保存为“豆瓣电影TOP250信息及评论.xlsx”文件,如图5.1所示。要求:先进行流程和函数设计,画出流程图,写出每个函数的接口设计(包括函数名、作用、输入、输出等),然后进行函数的编码和实现,最后组合成一个完整的爬虫程序。',
'description': '本教程将带你使用 Python 编写爬虫,自动爬取豆瓣电影 TOP250 排行榜中 250 部影片的基本信息和评论,并利用 BeautifulSoup4 库进行数据解析,最终将结果保存为 Excel 文件。',
'keywords': 'Python 爬虫, 豆瓣电影, TOP250, BeautifulSoup4, pandas, 数据提取, 数据分析, Excel',
'content': '流程图如下:\n\nplaintext\n开始 -> 爬取列表页 -> 提取基本信息 -> 提取热门短评 -> 保存为Excel文件 -> 结束\n\n\n函数接口设计如下:\n\n1. get_html(url) -> str\n - 作用:向指定的URL发送请求,获取网页的HTML内容\n - 输入:url(str):要请求的URL地址\n - 输出:html(str):网页的HTML内容\n\n2. parse_basic_info(html) -> List[Dict[str, str]]\n - 作用:解析电影的基本信息(排名、海报、片名、评分、导演、主演、上映时间、上映地点、类型)\n - 输入:html(str):网页的HTML内容\n - 输出:movies(List[Dict[str, str]]):电影的基本信息列表,每个电影的信息以字典形式存储\n\n3. parse_hot_comments(html) -> List[str]\n - 作用:解析电影的热门短评\n - 输入:html(str):网页的HTML内容\n - 输出:comments(List[str]):电影的热门短评列表\n\n4. save_to_excel(movies, comments) -> None\n - 作用:将电影的基本信息和热门短评保存为Excel文件\n - 输入:movies(List[Dict[str, str]]):电影的基本信息列表\n comments(List[str]):电影的热门短评列表\n - 输出:无\n\n5. main() -> None\n - 作用:主函数,用于执行爬取豆瓣电影TOP250信息的整个流程\n - 输入:无\n - 输出:无\n\n下面是完整的爬虫程序实现:\n\npython\nimport requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\n\ndef get_html(url):\n response = requests.get(url)\n return response.text\n\n\ndef parse_basic_info(html):\n soup = BeautifulSoup(html, 'html.parser')\n items = soup.find_all('div', class_='item')\n\n movies = []\n for item in items:\n rank = item.find('em').text\n poster = item.find('img')['src']\n title = item.find('span', class_='title').text\n score = item.find('span', class_='rating_num').text\n info = item.find('div', class_='bd').p.text.strip().split('\n')\n director = info[0].strip().split(':')[1].strip()\n actors = info[1].strip().split(':')[1].strip()\n year = info[2].strip().split('/')[0].strip()\n location = info[2].strip().split('/')[1].strip()\n genres = info[2].strip().split('/')[2].strip()\n\n movie = {\n '排名': rank,\n '海报': poster,\n '片名': f'<a href='{item.find('a')['href']}'>{title}</a>',\n '评分': score,\n '导演': director,\n '主演': actors,\n '上映时间': year,\n '上映地点': location,\n '类型': genres,\n '热门短评': ''\n }\n movies.append(movie)\n\n return movies\n\n\ndef parse_hot_comments(html):\n soup = BeautifulSoup(html, 'html.parser')\n items = soup.find_all('div', class_='comment-item')\n\n comments = []\n for item in items[:5]:\n comment = item.find('span', class_='short').text\n comments.append(comment)\n\n return comments\n\n\ndef save_to_excel(movies, comments):\n df = pd.DataFrame(movies)\n df['热门短评'][:10] = ['\n'.join([f'{i+1}.{comment}' for i, comment in enumerate(comments)])] + [''] * 9\n df.to_excel('豆瓣电影TOP250信息及评论.xlsx', index=False)\n\n\ndef main():\n url = 'https://movie.douban.com/top250'\n html = get_html(url)\n movies = parse_basic_info(html)\n\n for movie in movies[:10]:\n movie_url = movie['片名'].split(''')[1]\n movie_html = get_html(movie_url)\n comments = parse_hot_comments(movie_html)\n movie['热门短评'] = comments\n\n save_to_excel(movies, comments)\n\n\nif __name__ == '__main__':\n main()\n\n\n请注意,由于豆瓣网站的反爬虫机制,可能需要设置headers以模拟浏览器访问。另外,该程序使用了pandas库来保存数据为Excel文件,请确保已安装该库。
原文地址: https://www.cveoy.top/t/topic/psad 著作权归作者所有。请勿转载和采集!