今天用到BeautifulSoup解析爬下來(lái)的網(wǎng)頁(yè)數(shù)據(jù)
首先導(dǎo)入包from bs4 import BeautifulSoup
然后可以利用urllib請(qǐng)求數(shù)據(jù)
記得要導(dǎo)包
1
|
import urllib.request |
然后調(diào)用urlopen,讀取數(shù)據(jù)
1
2
|
f = urllib.request.urlopen(‘http: / / jingyan.baidu.com / article / 455a9950bc94b8a166277898 .html‘) response = f.read() |
這里我們就不請(qǐng)求數(shù)據(jù)了,直接用本地的html代碼,如下
注意:”'xxx”'是多行注釋
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
#python3 from bs4 import BeautifulSoup html = '''<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è)對(duì)象,接下來(lái)獲取對(duì)象的相關(guān)屬性 html = BeautifulSoup(html, 'html.parser' ) # 讀取title內(nèi)容 print (html.title) # 讀取title屬性 attrs = html.title.attrs print (attrs) # 獲取屬性attrs['class'] ---->['ceshi'] 這是一個(gè)list 通過(guò)下標(biāo)可以獲取值 print (attrs[ 'class' ][ 0 ]) # 讀取body print (html.body) 讀取數(shù)據(jù)還可以通過(guò)BeautifulSoup的select方法 html.select() #按標(biāo)簽名查找 soup.select( 'title' ) soup.select( 'body' ) # 按類(lèi)名查找 soup.select( '.sister' ) # 按id名查找 # p標(biāo)簽中id為link的標(biāo)簽 soup.select( 'p #link' ) #取標(biāo)簽里面的值 soup.p.string #取標(biāo)簽里屬性值 通過(guò)href獲取 html[ 'href' ] |
以上這篇python3爬蟲(chóng)獲取html內(nèi)容及各屬性值的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/lzq520210/article/details/76855606