iT邦幫忙

0

1. Python大數據特訓班_爬取與分析_2.)BeautifulSoup

Zoey 2019-03-04 23:50:545291 瀏覽

大家好,我是Zoey
今天是第二天發文,還有很多不足,
還請多多包涵,有錯誤可以糾正我喔!!!!
謝謝!!/images/emoticon/emoticon41.gif

BeautifulSoup:網頁解析

使用BeautifulSoup時須先安裝模組

安裝命令

pip install BeautifulSoup

其實上一章節就有用到BeautifulSoup了
BeautifulSoup的使用方法

#引入BeautifulSoup
from bs4 import BeautifulSoup
#使用BeautifulSoup解讀原始碼
BeautifulSoup 物件=BeautifulSoup(原始碼,'html.parser')

示範使用BeautifulSoup模組解讀

#引入BeautifulSoup模組
from bs4 import BeautifulSoup
#html原始碼
my_html="""
<html><head><title>天天長高</title></head>
<body><h2>數的羊都跑了</h2>
<div class="item">
    <a id="link1" href="##">Link 1</a>
    <a id="link2" href="##">Link 2</a>
</div>
</body></html>
"""
#使用BeautifulSoup作解析
sp=BeautifulSoup(my_html,'html.parser')

常用的BeautifulSoup的屬性方法

  • tag名稱:回傳指定tag內容
print(sp.title)

結果為 天天長高

  • text:去除所有html標籤後回傳文字內容
print(sp.text)

結果為
天天長高
數的羊都跑了

Link 1
Link 2

  • find("標籤名稱"):傳回第一個符合條件的tag
print(sp.find("a"))

結果為
Link 1

  • find_all("標籤名稱"):回傳所有符合條件的內容
    找到內容會回傳一個串列
print(sp.find_all("a"))

解果為
[Link 1, Link 2]

-find和find_all也可以尋找符合屬性的內容
find或find_all(標籤名稱,{屬性名稱:屬性內容})

print(sp.find("a",{"id":"link2"}))

結果為
Link 2

  • select():回傳指定id或class
    使用id時前面必加#
    使用class時前面必加.
    select回傳值會是串列
print(sp.select("title"))
#id使用方法
print(sp.select("#link1"))
#class使用方法
print(sp.select(".item"))

結果為
[天天長高]
[Link 1]
[
Link 1
Link 2

有多層標籤或id或類別時也可以堆疊使用

print(sp.select("html head title"))

結果為
[天天長高]

取得標籤的屬性內容
可以使用get方法或是字典的方式

回傳值.get("屬性名稱")
回傳值["屬性名稱"]


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言