python爬蟲-html解析器beautifulsoup


 

 

看排版更好的原文地址

 

BeautifulSoup庫是解析、遍歷、維護“標簽樹”的功能庫

安裝

sudo pip install beautifulsoup4

使用

# coding: UTF-8
import requests
url="http://www.baidu.com"
r=requests.get(url)
r.encoding=r.apparent_encoding
print r.text

結果:
這里寫圖片描述
上面的代碼以前寫過,就是獲取百度的源代碼。現在我們就通過這個源代碼來學習beautifulsoup庫的使用吧

soup.prettify()

對源代碼進行美化(格式化)
# coding: UTF-8
import requests
from bs4 import BeautifulSoup
url="http://www.baidu.com"
r=requests.get(url)
r.encoding=r.apparent_encoding
#將源代碼保存到變量s里面
s=r.text
soup=BeautifulSoup(s,"html.parser")
s=soup.prettify()
print s

結果:(確實好看多了)
這里寫圖片描述
from bs4 import
引入BeautifulSoup類

代碼中構建了一個BeautifulSoup類型的對象soup,參數為網頁源代碼和”html.parser”,表明是解析html的。

soup=BeautifulSoup(s,"html.parser")

上面的代碼是通過字符串里面的源代碼構建BeautifulSoup類對象,還可以像下面這樣直接使用本地html文件創建BeautifulSoup類對象。

soup=BeautifulSoup(open("a.html"),"html.parser")

基本元素說明

這里寫圖片描述

例子

  • title
    標題標簽
print soup.title

結果:
這里寫圖片描述

  • a
    鏈接標簽
print soup.a

結果:
這里寫圖片描述
tips:有多個時只返回第一個
* name
顯示標簽的名字

print soup.a.name

這里寫圖片描述

  • parent
    得到標簽的父標簽,是一個bs4.element.Tag對象
int soup.a.parent.name
print soup.a.parent.parent.name
print soup.a.parent.parent.parent.parent.parent.name

這里寫圖片描述

  • attrs
    得到標簽屬性,是一個字典
print soup.a.attrs

attrs
如果要獲取字典中的一個值,可以通過:

print soup.a.attrs["class"]

class是字典的一個key,返回它對應的value
這里寫圖片描述

print soup.a.attrs["href"]
```獲取鏈接
```tips:在python里面可以用type()獲取變量的類型``` * string
獲取尖括號之間的字符串




<div class="se-preview-section-delimiter"></div>

print soup.a.string
“`

print soup.a.string

是一個bs4.element.NavigableString類型的對象
這里寫圖片描述

為了便於比較,附a的圖:

這里寫圖片描述

  • 小結

這里寫圖片描述

html的遍歷

這里寫圖片描述

contents

子節點的列表,list類型

soup=BeautifulSoup("<body><p>1111</p><p>2222</p></body>","html.parser")
print soup.body.contents

這里寫圖片描述
得到列表元素:

list=soup.body.contents
print list[1]

這里寫圖片描述

tips:index從0開始,list[0],list[1]

children

得到標簽的子節點,為listiterator(迭代)類型

for child in soup.body.children:
    print child

遍歷兒子節點
這里寫圖片描述

parent

節點的父親標簽

parents

先輩標簽的迭代類型

平行遍歷

(同一個父節點的標簽之間)
這里寫圖片描述

  • 總結

這里寫圖片描述

 

http://hjwblog.com/2018/03/22/%E5%AE%89%E5%8D%93/%E5%AE%89%E5%8D%93%E5%BC%80%E5%8F%91-intent%E5%9C%A8Activity%E4%B9%8B%E9%97%B4%E6%95%B0%E6%8D%AE%E4%BC%A0%E9%80%92/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM