Python爬取豆瓣Top250电影介绍教程
你可以使用 Python 的 requests 和 BeautifulSoup 库来爬取豆瓣 Top250 电影的介绍。下面是一个示例代码,演示了如何实现:
import requests
from bs4 import BeautifulSoup
def get_movie_details(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
movie_list = soup.find_all('div', class_='hd')
for movie in movie_list:
movie_name = movie.a.span.text
movie_url = movie.a['href']
movie_response = requests.get(movie_url)
movie_soup = BeautifulSoup(movie_response.text, 'html.parser')
movie_intro = movie_soup.find('span', property='v:summary').text.strip()
print(f'电影名称:{movie_name}')
print(f'电影介绍:{movie_intro}')
print('------------------------------')
def scrape_top250_movies():
for page in range(0, 250, 25):
url = f'https://movie.douban.com/top250?start={page}'
get_movie_details(url)
scrape_top250_movies()
上述代码通过定义两个函数来实现。get_movie_details 函数用于获取每个电影的名称和链接,并进一步访问链接获取电影的介绍。scrape_top250_movies 函数用于循环遍历豆瓣 Top250 电影的页面,并调用 get_movie_details 函数获取详细信息。
这段代码将打印每部电影的名称和介绍,你可以根据需要进行进一步处理,例如将数据保存到文件或数据库中。
请注意,爬取网站内容时要遵守该网站的使用条款并尊重网站的访问频率限制。此外,豆瓣网站可能会对爬虫进行反爬虫措施,所以请谨慎使用此代码,并确保你的爬取行为合法、合规。
原文地址: https://www.cveoy.top/t/topic/PZk 著作权归作者所有。请勿转载和采集!