首页 > 技术文章 > 010 python接口 bs4解析html

huafan 2018-11-03 09:11 原文

 

 

'''
时间:2018/11/03
功能:bs4解析html
目录:
    一: 学习使用  
        1 官网介绍
        2 安装Beautiful Soup
        3 四种对象
            (1) 全部
            (2) 标签
            (3) 字符
            (4) 注释
    二: 实战使用
'''

 

一: 学习使用
  1 官网介绍

1 :  访问官网地址: https://beautifulsoup.readthedocs.io

2 :  可以查看介绍和使用。


  2 安装Beautiful Soup

1 : 运行输入"cmd",进入Dos窗口。

2 : 输入"pip install beautifulsoup4"(安装beautifulsoup4模块)。

 

1 : 输入"pip list"(查看安装的库)。

2 : 可以看见已经安装了beautifulsoup4 (4.6.3)。

 

1 : 输入"pip show beautifulsoup4"(查看beautifulsoup4的信息)。

 

  3 四种对象
    (1) 全部

<meta charset="UTF -8">  <! -- for HTML5 -- >
<meta http-equiv="Content-Type" content="text/html; charset=utf  -8"/> 
<html>

<head><title>汁虫</title></head>

<body>
<b><! -- Hey, this in comment!--></b >
<p class="title"><b>汁虫</b></p> 

<a href="https://www.cnblogs.com/huafan/category/1264131.html" class="sister" id="link1">fiddler</a>,
<a href="https://www.cnblogs.com/huafan/category/1282855.html" class="sister" id="link2" >python</a>,
<a href="https://www.cnblogs.com/huafan/category/1264133.html" class="sister" id="link3" >python</a>,

快来关注吧!</p> 
<p class="story">...</p>

1 : 使用这份html做测试文档,命名为"汁虫.html"。

 

# coding:utf-8
from bs4 import BeautifulSoup

# 打开文件
yo = open("汁虫.html",  # 文件路径 - 同一级目录不需要写路径
          "rb")          # 打开方式 - 读取

# 全部显示 - html
soup = BeautifulSoup(yo,            # 文件的对象
                     "html.parser") # 解析器名称
print(soup, end="\n\n") # 打印内容
print(type(soup))       # 打印类型
<meta charset="utf-8"/> <!-- -- for HTML5 -- -->
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<html>
<head><title>汁虫</title></head>
<body>
<b><!-- -- Hey, this in comment!----></b>
<p class="title"><b>汁虫</b></p>
<a class="sister" href="https://www.cnblogs.com/huafan/category/1264131.html" id="link1">fiddler</a>,
<a class="sister" href="https://www.cnblogs.com/huafan/category/1282855.html" id="link2">python</a>,
<a class="sister" href="https://www.cnblogs.com/huafan/category/1264133.html" id="link3">python</a>,

快来关注吧!</body></html></meta>
<p class="story">...</p>

<class 'bs4.BeautifulSoup'>

1 : 打印全部html内容。

 

    (2) 标签

# coding:utf-8
from bs4 import BeautifulSoup


# 打开文件
yo = open("汁虫.html",    # 文件路径 - 同一级目录不需要写路径
          "rb")          # 打开方式 - 读取
soup = BeautifulSoup(yo,            # 文件的对象
                     "html.parser") # 解析器名称

# 获取标签
print(soup.title)     # 获取标签

print(soup.p.b)       # 多层标签

print(soup.a)         # 获取标签: 相同名称 - 获取第一个
<title>汁虫</title>
<b>汁虫</b>
<a href="https://www.cnblogs.com/huafan/category/1264131.html class=" id="link1" sister"="">fiddler</a>

1 : 打印全部html中标签内容。

 

# coding:utf-8
from bs4 import BeautifulSoup


# 打开文件
yo = open("汁虫.html",  # 文件路径 - 同一级目录不需要写路径
          "rb")         # 打开方式 - 读取
soup = BeautifulSoup(yo,            # 文件的对象
                     "html.parser") # 解析器名称


# 获取标签 - 属性
att = soup.a.attrs  # 标签属性 : 数据转换 - 字典类型
print(att)
print(att['href'])
print(att['class'][0])
print(att['id'])
{'href': 'https://www.cnblogs.com/huafan/category/1264131.html', 'class': ['sister'], 'id': 'link1'}
https://www.cnblogs.com/huafan/category/1264131.html
sister
link1

1 : 打印全部html中标签的属性。

 

# coding:utf-8
from bs4 import BeautifulSoup


# 打开文件
yo = open("汁虫.html",  # 文件路径 - 同一级目录不需要写路径
          "rb")          # 打开方式 - 读取
soup = BeautifulSoup(yo,            # 文件的对象
                     "html.parser") # 解析器名称

# 打印标签 - 相同标签
all = soup.find_all('a') # 获取list对象
for nLoop in all:
    print(nLoop)

# 打印输出 - 具体标签
print("")           # 换行输出
print(all[1])       # 获取标签 - 第二个
att = all[1].attrs  # 获取标签属性
print(att)
<a class="sister" href="https://www.cnblogs.com/huafan/category/1264131.html" id="link1">fiddler</a>
<a class="sister" href="https://www.cnblogs.com/huafan/category/1282855.html" id="link2">python</a>
<a class="sister" href="https://www.cnblogs.com/huafan/category/1264133.html" id="link3">python</a>

<a class="sister" href="https://www.cnblogs.com/huafan/category/1282855.html" id="link2">python</a>
{'href': 'https://www.cnblogs.com/huafan/category/1282855.html', 'class': ['sister'], 'id': 'link2'}

1 : 打印相同的标签。

 

    (3) 字符

# coding:utf-8
from bs4 import BeautifulSoup


# 打开文件
yo = open("汁虫.html",  # 文件路径 - 同一级目录不需要写路径
          "rb")          # 打开方式 - 读取
soup = BeautifulSoup(yo,            # 文件的对象
                     "html.parser") # 解析器名称


# 获取标签 - 字符串
print(soup.a.string)
fiddler

1 : 打印标签中的字符串。

 

1 : 获取目标网址中红框内容。

 

# coding:utf-8
import requests
import urllib3
urllib3.disable_warnings() # 忽略警告
from bs4 import BeautifulSoup

url = "https://www.qiushibaike.com/"
head = {
    "User-Agent" : "Fiddler"
}
r1 = requests.get(url, headers=head, verify = False)

soup = BeautifulSoup(r1.content, "html.parser")
all = soup.find_all(class_="content")   # 命名冲突 : html的class - python的class
for i in all:
    print(i.span.get_text().replace("\n", ""))    # get_text() : 获取标签下 - 所有文本

 

    (4) 注释

      (暂无)


二: 实战使用

 

1 : 下载目标网址: http://699pic.com/sousuo-218808-13-1-0-0-0.html 的图片。

 

# coding:utf-8
import requests
from bs4 import BeautifulSoup

url = "http://699pic.com/sousuo-218808-13-1-0-0-0.html"
r1 = requests.get(url, verify = False)

soup = BeautifulSoup(r1.content, "html.parser")
all = soup.find_all(class_ = "lazy") # 获取标签 - 所有标签
for i in all:
    # 异常情况处理
    try:
        jpg_url = i["data-original"]    # 获取地址 - 图片下载
        print(jpg_url, end="")          # 打印地址
        jpg_title = i["title"]          # 获取名称 - 图片命名
        print(jpg_title)                # 打印名称

        r2 = requests.get(jpg_url)      # 请求下载
        with open(jpg_title + ".jpg", "wb") as fp:  # 文件写入
            fp.write(r2.content)        # 写入图片
    except:
        pass

 

推荐阅读