2.2 BeautifulSoup 解析网页: CSS

CSS 的 Class

CSS 在装饰每一个网页部件的时候, 都会给它一个名字. 而且一个类型的部件, 名字都可以一样

里面的字体/背景颜色, 字体大小, 都是由 CSS 来掌控的, CSS 的代码, 可能就会放在这个网页的 < head> 中

from bs4 import BeautifulSoup
from urllib.request import urlopen

# if has Chinese, apply decode()
html = urlopen("https://morvanzhou.github.io/static/scraping/list.html").read().decode('utf-8')
print(html)
<head>
    ...
    <style>
    .jan {
        background-color: yellow;
    }
    ...
    .month {
        color: red;
    }
    </style>
</head>

<body>
...
<ul>
    <li class="month">一月</li>
    <ul class="jan">
        <li>一月一号</li>
        <li>一月二号</li>
        <li>一月三号</li>
    </ul>
    ...
</ul>
</body>

在 < head> 中,被放在 < style> 里面的都是某些 class 的 CSS 代码.,比如 jan 就是一个 class,jan 这个类掌控了这个类型的背景颜色,所以在 < ul class="jan"> 这里, 这个 ul 的背景颜色就是黄色的,而如果是 month 这个类, 它们的字体颜色就是红色

按 Class 匹配

找所有 class=month 的信息. 并打印出它们的 tag 内文字.

soup = BeautifulSoup(html, features='lxml')

# use class to narrow search
month = soup.find_all('li', {"class": "month"})
for m in month:
    print(m.get_text())

"""
一月
二月
三月
四月
五月
"""

找到 class=jan 的信息. 然后在 < ul> 下面继续找 < ul> 内部的< li> 信息

jan = soup.find('ul', {"class": 'jan'})
d_jan = jan.find_all('li')              # use jan as a parent
for d in d_jan:
    print(d.get_text())

"""
一月一号
一月二号
一月三号
"""

Last updated

Was this helpful?