Python 數(shù)據(jù)分析之Beautiful Soup 提取頁面信息
概述
數(shù)據(jù)分析 (Data Analyze) 可以在工作中的各個方面幫助我們. 本專欄為量化交易專欄下的子專欄, 主要講解一些數(shù)據(jù)分析的基礎(chǔ)知識.
Beautiful Soup
Beautiful 是一個可以從 HTML 或 XML 文件中提取數(shù)據(jù)的 Pyhton 庫. 簡單來說, 它能將 HTML 的標(biāo)簽文件解析成樹形結(jié)構(gòu), 然后方便的獲取到指定標(biāo)簽的對應(yīng)屬性.
安裝:
pip install beautifulsoup4
例子:
from bs4 import BeautifulSoup # 創(chuàng)建一段HTML代碼 html_content = """ <html> <head> <title>我是小白呀的博客</title> </head> <body> <p class="redColor">個人介紹</p> </body> </html> """ # 生成soup soup = BeautifulSoup(html_content, "html.parser") # 調(diào)試輸出 print(soup.title) # 標(biāo)題 print("name:", soup.title.name) print(soup.head) # 頭部 print("name:", soup.head.name) print(soup.p) # 段落 print("name:", soup.p.name) print("class:", soup.p.attrs)
輸出結(jié)果:
<title>我是小白呀的博客</title>
name: title
<head>
<title>我是小白呀的博客</title>
</head>
name: head
<p class="redColor">個人介紹</p>
name: p
class: {'class': ['redColor']}
class: ['redColor']
提取頁面信息
例子:
from urllib import request from bs4 import BeautifulSoup # 網(wǎng)頁 url = "https://iamarookie.blog.csdn.net/" # 發(fā)送請求 response = request.urlopen(url) # 獲取內(nèi)容 html_content = response.read().decode("utf-8") # 生成soup soup = BeautifulSoup(html_content) # 解析博客名字 blog_name = soup.find("div", attrs={"class":"user-profile-head-name"}).text print("博客名字:\n", blog_name) # 解析博客簽名 blog_signature = soup.find("div", attrs={"class":"user-profile-head-introduction"}).text print("博客簽名:\n", blog_signature.strip())
輸出結(jié)果:
博客名字:
我是小白呀 碼齡2年
博客簽名:
吾本布衣, 出自紐約, 四周大山. 簞瓢屢空, 環(huán)堵蕭然, 不弊風(fēng)日. 吾好讀書, 滴水石穿, 笨鳥先飛, 求知不斷, 方能立足. 不羨孔北海之座上客常滿, 但求吾輩架上書常在. 涸轍遺鮒, 暮成枯, 人而無志, 與彼何殊. Self-study Computer Science. 愿為 open source 自效微力. 天高地闊,欲往觀之. 因為啥也不會, 默默做一只小白
到此這篇關(guān)于Python 數(shù)據(jù)分析之Beautiful Soup 提取頁面信息的文章就介紹到這了,更多相關(guān)Python Beautiful Soup內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。