Python抓取豆瓣电影Top250
文章简介
在本篇文章中,我们将探讨如何利用Python编程语言中的requests
库和BeautifulSoup
库来抓取豆瓣网站上电影Top250的数据信息。通过本文的学习,读者将掌握基本的网络爬虫技巧,了解如何解析HTML文档,以及怎样高效地处理和存储抓取到的数据。
1. 前言
简要介绍为什么选择豆瓣Top250作为抓取目标,以及这项任务可能带来的价值或学习点。
2. 准备工作
安装必要的库
pip install requests beautifulsoup4
3. 详细代码
import requests
from bs4 import BeautifulSoup
import time
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36'
}
# 定义函数来获取并解析单页内容
def fetch_page(start):
url = f'https://movie.douban.com/top250?start={start}'
try:
response = requests.get(url, headers=headers)
response.raise_for_status() # 如果响应状态码不是200,抛出HTTPError
return response.text
except requests.RequestException as e:
print(f"An error occurred: {e}")
return None
# 定义函数来解析HTML并提取电影信息
def parse_html(html):
soup = BeautifulSoup(html, 'html.parser')
movies = []
for item in soup.select('div.item'):
title = item.find('span', class_='title').get_text()
link = item.find('a')['href']
movies.append((title, link))
return movies
# 主程序逻辑
with open('豆瓣电影T250.txt', 'w', encoding='utf-8') as fp:
for start in range(0, 250, 25):
html = fetch_page(start)
if html:
movies = parse_html(html)
for title, link in movies:
fp.write(f'{link}\t{title}\n') # 写入链接和标题,并添加换行符
time.sleep(1) # 每次请求后等待一秒,以减轻服务器负担
print("数据抓取完成")