1. 程式人生 > >010 python介面 bs4解析html

010 python介面 bs4解析html

 

 

'''
時間: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 href="https://www.cnblogs.com/huafan/category/1264131.html class=" id="link1" sister"="">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'>

 

    (2) 標籤


    (3) 字元
    (4) 註釋
二: 實戰使用