首页 > 应用开发 > Python > Python爬虫实战:从入门到精通
# 安装必要的库pip install requests beautifulsoup4
import requests
from bs4 import BeautifulSoup
def fetch_douban_top250():
url = 'https://movie.douban.com/top250'
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3'
}
response = requests.get(url, headers=headers)
soup = BeautifulSoup(response.text, 'html.parser')
# 定位电影列表
movies = soup.find_all('div', class_='item')
for movie in movies:
title = movie.find('span', class_='title').get_text()
rating = movie.find('span', class_='rating_num').get_text()
review = movie.find('div', class_='star').find_all('span')[-1].get_text()
print(title, rating, review)
if __name__ == '__main__':
fetch_douban_top250()
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70026917/viewspace-3018128/ ,如需转载,请注明出处,否则将追究法律责任。