前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Beautiful Soup与运用(猫眼电影榜单)

Beautiful Soup与运用(猫眼电影榜单)

作者头像
机器视觉CV
发布2019-07-15 17:52:09
5190
发布2019-07-15 17:52:09
举报
文章被收录于专栏:机器视觉CV

简介

Beautiful Soup是Python的一个HTML/XML的解析库,可以用来获取网页信息 输入文档为Unicode 编码,输出文档为UTF-8编码,不需考虑编码问题

Beautiful Soup安装

  • pip3 install Beautiful Soup4
  • wheel安装

用法

基本用法

  • 选择用LXML解析器
代码语言:javascript
复制
from bs4 import BeautifulSoup
html = """<html><head><title>The Dormouse's story</title></head><body><p class="title" name="dromouse"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" id="link1"><!-- Elsie --></a>,<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p><p class="story">...</p>"""
soup = BeautifulSoup(html, 'lxml')
print(soup.prettify())#以标准的缩进格式输出print(soup.title.string)
  • 节点选择器

在此可以认为soup是一锅汤,soup.节点 就是选择相应的食材

  • 获取名称

语法格式:soup.节点.name 如soup.p.title

  • 获取属性

soup.节点名['属性名'] 如soup.p[class'] soup.p.attrs #获取该节点的所有属性和值

  • 获取内容

语法格式:soup.节点.string

print(soup.p.string)#打印p节点的文本内容

  • 嵌套选择

语法格式:soup.父节点.子节点

soup.p.a

  • 关联选择

子节点:children 只显示其下面一层的节点及内容

代码语言:javascript
复制
print(soup.p.children)for i, child in enumerate(soup.p.children):
    print(i,child)

子孙节点:descendants 显示其下面一层的子孙节点及内容

代码语言:javascript
复制
print(soup.p.descendants)for i, child in enumerate(soup.p.descendants):
    print(i, child)

父节点:parent

代码语言:javascript
复制
print(soup.a.parent)

父节点之外的祖父节点:parents

代码语言:javascript
复制
for i, parent in enumerate(soup.a.parents):
    print(i, parent)

兄弟节点(同级节点): nextsibling(下一个) prvioussibling(前一个), nextsiblings(之后所有) previoussiblings(前面所有)

代码语言:javascript
复制
print('Next Sibling', soup.a.next_sibling)
print('Prev Sibling', soup.a.previous_sibling)
print('Next Siblings', list(enumerate(soup.a.next_siblings)))
print('Prev Siblings', list(enumerate(soup.a.previous_siblings)))

这类语法只会匹配第一个节点,后面的将会被忽略

方法选择器

  • 节点选择器:

通过属性选择,这种方法快,但是复杂选择就比较繁琐

  • 方法选择器:灵活

find_all() 返回所有元素

代码语言:javascript
复制
find_all(name , attrs , recursive , text , **kwargs)

name参数: soup.findall(name='ul') attrs参数print(soup.findall(attrs={'class': 'list'})) text参数print(soup.find_all(text=re.compile('hello', re.I))) find() 返回单个元素

  • 其他

findparents()和findparent():前者返回所有祖先节点,后者返回直接父节点。

findnextsiblings()和findnextsibling():前者返回后面所有的兄弟节点,后者返回后面第一个兄弟节点。

findprevioussiblings()和findprevioussibling():前者返回前面所有的兄弟节点,后者返回前面第一个兄弟节点。

findallnext()和find_next():前者返回节点后所有符合条件的节点,后者返回第一个符合条件的节点。

findallprevious()和find_previous():前者返回节点后所有符合条件的节点,后者返回第一个符合条件的节点。

CSS选择器

爬取猫眼电影排行榜

程序

代码语言:javascript
复制
import requestsfrom bs4 import BeautifulSoupimport refrom requests.exceptions import RequestException
base_url = 'http://maoyan.com/board/4?offset='def parse(html_info):
    soup = BeautifulSoup(html_info, 'lxml')
    indexs = re.findall('board-index.*?>(\d+)<', html_info)
    names = soup.find_all(attrs={'class', 'name'})
    stars = soup.find_all(attrs={'class', 'star'})
    releasetimes = soup.find_all(attrs={'class', 'releasetime'})
    scores_integers = soup.find_all(attrs={'class', 'integer'})
    scores_fractions = soup.find_all(attrs={'class', 'fraction'})    for index, name, star, releasetime, scores_integer, scores_fraction in zip(indexs, names, stars, releasetimes, scores_integers, scores_fractions):
        movie_list = {'index': index, 'name': name.string, 'star': star.string.strip(), 'releasetime': releasetime.string,                      'score': str(scores_integer.string) + str(scores_fraction.string)}
        print(movie_list)def get_onepage(url):
    try:
        headers = {            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.84 Safari/537.36'
        }
        response = requests.get(url, headers=headers)        if response.status_code == 200:            return response.text        return None
    except RequestException:        return Noneif __name__ == '__main__':    for i in range(10):
        html = get_onepage(base_url+str(i*10))
        parse(html)

输出结果

代码语言:javascript
复制
{'index': '1', 'name': '霸王别姬', 'star': '主演:张国荣,张丰毅,巩俐', 'releasetime': '上映时间:1993-01-01(中国香港)', 'score': '9.6'} 
{'index': '2', 'name': '肖申克的救赎', 'star': '主演:蒂姆·罗宾斯,摩根·弗里曼,鲍勃·冈顿', 'releasetime': '上映时间:1994-10-14(美国)', 'score': '9.5'} 
{'index': '3', 'name': '罗马假日', 'star': '主演:格利高里·派克,奥黛丽·赫本,埃迪·艾伯特', 'releasetime': '上映时间:1953-09-02(美国)', 'score': '9.1'} 

{'index': '4', 'name': '这个杀手不太冷', 'star': '主演:让·雷诺,加里·奥德曼,娜塔莉·波特曼', 'releasetime': '上映时间:1994-09-14(法国)', 'score': '9.5'}
{'index': '5', 'name': '教父', 'star': '主演:马龙·白兰度,阿尔·帕西诺,詹姆斯·肯恩', 'releasetime': '上映时间:1972-03-24(美国)', 'score': '9.3'} 
{'index': '6', 'name': '泰坦尼克号', 'star': '主演:莱昂纳多·迪卡普里奥,凯特·温丝莱特,比利·赞恩', 'releasetime': '上映时间:1998-04-03', 'score': '9.5'}
{'index': '7', 'name': '龙猫', 'star': '主演:日高法子,坂本千夏,糸井重里', 'releasetime': '上映时间:1988-04-16(日本)', 'score': '9.2'}
{'index': '8', 'name': '唐伯虎点秋香', 'star': '主演:周星驰,巩俐,郑佩佩', 'releasetime': '上映时间:1993-07-01(中国香港)', 'score': '9.2'}
{'index': '9', 'name': '千与千寻', 'star': '主演:柊瑠美,入野自由,夏木真理', 'releasetime': '上映时间:2001-07-20(日本)', 'score': '9.3'}
{'index': '10', 'name': '魂断蓝桥', 'star': '主演:费雯·丽,罗伯特·泰勒,露塞尔·沃特森', 'releasetime': '上映时间:1940-05-17(美国)', 'score': '9.2'}
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2018-10-01,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 机器视觉CV 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 简介
  • Beautiful Soup安装
  • 用法
    • 基本用法
      • 方法选择器
        • CSS选择器
        • 爬取猫眼电影排行榜
        领券
        问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档