Python爬虫,使用BeautifulSoup爬取豆瓣电影TOP250电影信息(BeautifulSoup, lxml)

上一篇:Python爬虫,通过正则表达式爬取豆瓣电影TOP250的图片,https://blog.csdn.net/licx1988/article/details/102869923

本篇,使用BeautifulSoup进行解析,

解析库:BeautifulSoup
解析器:lxml
方法选择器:find()和find_all()

BeautifulSoup的官方文档:https://www.crummy.com/software/BeautifulSoup/bs4/doc.zh/

本文包括的知识点:requests,BeautifulSoup, lxml ,find(), find_all()等。
主要目标:抓取豆瓣电影TOP250的 电影名称等信息。
#通过 lxml ,find(), find_all()等方法,抓取豆瓣电影TOP250的 电影名称等信息
import requests
from bs4 import BeautifulSoup
from requests.exceptions import RequestException
import time

headers = {
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 '
                  '(KHTML, like Gecko) Chrome/78.0.3904.70 Safari/537.36'
}


def get_page(url):
    try:
        response = requests.get(url)
        if response.status_code == 200:
            return response.text
        return None
    except RequestException:
        print("请求页面出错……")


def parse_page(html):
    soup = BeautifulSoup(html, 'lxml')
    for div in soup.find_all(attrs={'class': 'item'}):  # 找到单个电影,找到class属性值为item的div标签;
       yield {
            'name': div.find('img').get('alt'),   # 电影的名称,在img标签下,提取 alt的属性值
            'rank': div.find('em').string,  # 获取电影的排名,提取em标签的文本内容;
            'score': div.find(class_='rating_num').string,  # 电影的评分,先找到class属性值为rating_num的span标签,提取span的标签的文本内容
            'movie_url': div.find('a').get('href'),     # 电影的链接,在a标签下,提取href的属性值
            'movie_pic_url': div.find('img').get('src')  # 电影封面的地址,在img标签下,提取 src的属性值
        }


def main(start):
    url = 'https://movie.douban.com/top250?start=' + str(start)
    html = get_page(url)
    for item in parse_page(html):
        print(item)


if __name__ == '__main__':
    for i in range(10):
        main(i*25)
        time.sleep(2)
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

13线

谢谢鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值