今天用到BeautifulSoup解析爬下來的網(wǎng)頁數(shù)據(jù)
首先導(dǎo)入包from bs4 import BeautifulSoup
然后可以利用urllib請求數(shù)據(jù)
記得要導(dǎo)包
import urllib.request
然后調(diào)用urlopen,讀取數(shù)據(jù)
f=urllib.request.urlopen(‘http://jingyan.baidu.com/article/455a9950bc94b8a166277898.html‘) response=f.read()
這里我們就不請求數(shù)據(jù)了,直接用本地的html代碼,如下
注意:”'xxx”'是多行注釋
#python3from bs4 import BeautifulSouphtml='''<html><head> <title class='ceshi'>super 哈哈 star</title></head><body> 天下第一帥 <p class='sister'> 是不是 </p></body></html>'''#用BeautifulSoup解析數(shù)據(jù) python3 必須傳入?yún)?shù)二'html.parser' 得到一個(gè)對象,接下來獲取對象的相關(guān)屬性html=BeautifulSoup(html,'html.parser')# 讀取title內(nèi)容print(html.title)# 讀取title屬性attrs=html.title.attrsprint(attrs)# 獲取屬性attrs['class'] ---->['ceshi'] 這是一個(gè)list 通過下標(biāo)可以獲取值print(attrs['class'][0])# 讀取bodyprint(html.body)讀取數(shù)據(jù)還可以通過BeautifulSoup的select方法html.select()#按標(biāo)簽名查找 soup.select('title')soup.select('body')# 按類名查找soup.select('.sister')# 按id名查找# p標(biāo)簽中id為link的標(biāo)簽soup.select('p #link')#取標(biāo)簽里面的值soup.p.string#取標(biāo)簽里屬性值 通過href獲取html['href']以上這篇python3爬蟲獲取html內(nèi)容及各屬性值的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持VEVB武林網(wǎng)。
新聞熱點(diǎn)
疑難解答
圖片精選