上一篇: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)