简单的Python爬虫案例

128 阅读1分钟
pythonCopy code
import requests
from bs4 import BeautifulSoup

def get_movie_list(url):
    # 发送HTTP GET请求获取网页内容
    response = requests.get(url)
    # 使用BeautifulSoup解析HTML内容
    soup = BeautifulSoup(response.text, 'html.parser')
    # 获取包含电影信息的标签列表
    movie_items = soup.find_all('div', class_='hd')
    # 遍历每个电影标签,提取电影名称
    movie_list = []
    for movie_item in movie_items:
        movie_name = movie_item.a.span.text.strip()
        movie_list.append(movie_name)
    return movie_list

def main():
    url = 'https://movie.douban.com/top250'
    movie_list = get_movie_list(url)
    for idx, movie in enumerate(movie_list, 1):
        print(f'{idx}. {movie}')

if __name__ == '__main__':
    main()

这个爬虫会爬取豆瓣电影Top250页面的电影名称,并输出到控制台。你可以将get_movie_list函数中的内容更改为提取其他感兴趣的信息,比如电影的评分、导演、演员等。