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