1. 程式人生 > >Python學習筆記——使用BeautifulSoup剖析頁面元素

Python學習筆記——使用BeautifulSoup剖析頁面元素

將網頁讀入Beautisoup中

接上回的程式碼,得到新浪的網頁。

import requests
url = 'https://www.sina.com.cn/'
res = requests.get(url)
res.encoding = 'utf-8'
print(res.text)

將得到的頁面讀入BeautifulSoup中

from bs4 import BeautifulSoup
# 讀入網頁, res.text 傳入剖析的網頁,html.parser 是一個剖析器
soup = BeautifulSoup(res.text, 'html.parser')
print(soup.text)

這裡的soup.text 和上面的res.text 是有區別的,將res.text讀入BeautifulSoup
中後,會把外部不需要的html , body 等標籤去除。

取得包含制定標籤的html元素

使用select找出指定標籤元素

# 使用select找出含有a標籤的元素
finds= soup.select('a')
print(finds)

因為頁面中含有a標籤的元素不會只有一個,所以select預設的返回值是一個列表,我們可以通過下標的方式得到指定的標籤。

# 顯示找到的第一個含有a標籤的元素
print(finds[
0]) # 顯示第一個含有a標籤的元素的文字 print(finds[0].text) # 取得a標籤內的連結 print(finds[0]['href'])

標籤內的屬性會被包裝成一個字典,所以我們可以通過中括號的形式取得裡面的值。

取得含有制定class屬性的元素

# 取得含有屬性 title 的元素
finds = soup.select('.title')
# 顯示所有class 為title的元素
for find in finds:
	print(find)

取得新浪頁面的標題和連結

import requests
from bs4 import BeautifulSoup

# 抓取的網頁的路徑 
url = 'https://news.sina.com.cn/china/' # 爬取頁面,接收響應 res = requests.get(url) # 設定頁面編碼 res.encoding = 'utf-8' # 將爬取的頁面放入BeautifulSoup soup = BeautifulSoup(res.text, 'html.parser') # 篩選頁面中的所有a標籤 links = soup.select('a') # 顯示所有的a標籤和連結地址 for link in links: print(link.text, '/t',link['href'])