BeautifulSoup模块

python学习-BeautifulSoup模块

BeautifulSoup 是Python的一个库,最主要的功能就是从网页爬取我们需要的数据。BeautifulSoup将 html 解析为对象进行处理,全部页面转变为字典或者数组,相对于正则表达式的方式,可以大大简化处理过程。

BeautifulSoup 解析

//ex.py


# -*- coding: utf-8 -*-

import re
import requests
from bs4 import BeautifulSoup

headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"}
response = requests.get('https://www.zhihu.com', headers = headers)
response.encoding = 'utf-8'
html = response.text

soup = BeautifulSoup(html, "html.parser")

# 标签查找
print(soup.meta)    # 查找第一个 meta 标签
print(soup.find('meta'))    # 查找第一个 meta 标签
print(soup.find_all('meta'))    # 列表形式返回 meta 标签

# 返回标签属性
print(soup.meta.get('charset'))    # 返回第一个 meta 标签的 charset 属性内容,多属性会返回一个列表
print(soup.meta['charset'])    # 返回第一个 meta 标签的 charset 属性内容
print(soup.meta.attrs)    # 以字典形式返回第一个 meta 标签的所有属性及内容

'''
out:
utf-8
utf-8
{'charset': 'utf-8'}
[Finished in 1.0s]
'''

# 返回标签名称
print(soup.meta.name)
'''
out:
meta
'''

# 返回 title 标签 <title>string<\title> 中的 string 部分
print(soup.title.string)

# 因为 meta 是 head 的子标签,所以以下输出一样
print(soup.head.meta)
print(soup.meta)

# 以列表形式返回 head 子标签
print(soup.head.contents)
print([child for child in soup.head.children])

# 以列表形式返回 head 子标签及子子标签
print([child for child in soup.head.descendants])
# 打印 head 子标签及子子标签
[print(child) for child in soup.head.descendants]

# 输出所有所有文本内容
[print(str) for str in soup.head.strings]
# 输出所有所有文本内容,去除空格或空行
[print(str) for str in soup.head.stripped_strings]

# 搜索所有 meta 标签并返回属性 content="IE=edge,chrome=1" 的标签
print(soup.head.find_all('meta', content="IE=edge,chrome=1"))
'''
out:
[<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible"/>]
'''

# 返回所有 m 开头的标签
for tag in soup.find_all(re.compile("^m")): 
    print(tag.name)
'''
out:
meta
meta
meta
meta
meta
meta
meta
main
mask
[Finished in 0.8s]
'''

# 找出所有的有 charset 属性的标签
print(soup.find_all(charset=True))
print(soup.find_all(charset="utf-8"))
'''
out:
[<meta charset="utf-8"/>]
[Finished in 0.8s]
'''

# 也可以通过字典或者组合方式进行查找
print(soup.find_all(attrs={"属性名": "属性值"}))
print(soup.find_all(href="https://static.zhihu.com/heifetz/main.app.216a26f4.046b812c09aa60a41379.css", rel="stylesheet"))

详细请看:
https://www.cnblogs.com/Jimc/p/10307947.html
https://blog.csdn.net/qq_36119192/article/details/82952442

posted @ 2021-02-10 23:47  Shivers0x72  阅读(77)  评论(0)    收藏  举报