Google Code Prettify - 輕量級的語法上色工具

星期三, 3月 13, 2019

Python 爬蟲 Beautiful Soup

# 引入 Beautiful Soup 模組
from bs4 import BeautifulSoup

# 以 Beautiful Soup 解析 HTML 程式碼
soup = BeautifulSoup(html_doc, 'html.parser')

# 原始 HTML 程式碼:在這邊我們先定義ㄧ個html類型的檔案
html_doc = """
<html><head><title>The Dormouse's story</title></head>
<body>
<p class="title"><b>The Dormouse's story</b></p>
<p class="story">Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
and they lived at the bottom of a well.</p>
<p class="story">...</p>
"""
# 輸出排版後的 HTML 程式碼
print(soup.prettify())

# 測試
soup.title.string
soup.find("a")
soup.find("a").text
soup.find("a").string
soup.find("a").get('id')
soup.find("a").get('href')
soup.find("a").get('class')
soup.find_all("a")
for link in soup.find_all('a'):
    print(link.get('href'))   # 輸出超連結

for tag in soup.find_all('a'):
    print(tag.string)    # 輸出超連結的文字


# CSS Select
soup.find_all(id="link3")
soup.select("title")
soup.select("body a ")
soup.select("body a ")[2]
soup.select("body a ")[2].text
soup.select("body a ")[2].string
soup.select("body a ")[2].get('id')
soup.select("body a ")[2].get('href')
soup.select("body a ")[2].get('class')

# 搜尋所有超連結與粗體字
soup.find_all(["a", "b"])

# 限制搜尋結果數量
soup.find_all(["a", "b"], limit=2) 

# 預設會以遞迴搜尋 
soup.html.find_all("title") 

# 不使用遞迴搜尋,僅尋找次一層的子節點 
soup.html.find_all("title", recursive=False)