日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) >

bpython bs4用哪个解释器好_针对python爬虫bs4(BeautifulSoup)库的基础问题

發(fā)布時(shí)間:2025/3/21 46 豆豆
生活随笔 收集整理的這篇文章主要介紹了 bpython bs4用哪个解释器好_针对python爬虫bs4(BeautifulSoup)库的基础问题 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

bs4(BeautifulSoup)庫(kù)的基本使用

1.導(dǎo)入模塊

from bs4 import BeautifulSoup

2.解析獲取到的網(wǎng)頁(yè)內(nèi)容

文檔被轉(zhuǎn)換成Unicode,并且HTML的實(shí)例都被轉(zhuǎn)換成Unicode編碼。

可以打印soup對(duì)象的內(nèi)容,格式化輸出:print soup.prettify()

url_str = getHTMLText(url)

soup = BeautifulSoup(url_str,'html.parser')

3.基本使用方法

bs4 將復(fù)雜的HTML文檔轉(zhuǎn)換成一個(gè)復(fù)雜的樹形結(jié)構(gòu),每個(gè)節(jié)點(diǎn)都是python的對(duì)象。

根據(jù)標(biāo)簽查找(type:bs4_obj)

head = soup.head

"""

百度一下,你就知道

"""

獲取屬性

title = head.title # 在soup中獲取第一個(gè)符合要求的標(biāo)記

#

百度一下,你就知道

title_str = name.string # 獲取標(biāo)簽內(nèi)部的文字

# 百度一下,你就知道

meta = head.meta

#

content = meta.get('content') # 獲取meta中第一個(gè)屬性

content = meta['content']

# text/html;charset=utf-8

content = meta.attrs # 獲取meta中所有屬性

# {'http-equiv': 'content-type', 'content': 'text/html;charset=utf-8'}

meta.name = 'hi' # 修改標(biāo)簽的name

meta['content'] = 'hello world' # 修改標(biāo)簽的屬性和內(nèi)容

print(meta)

#

獲取文本內(nèi)容

content = head.contents # 返回以head下各標(biāo)簽為元素的列表

"""

[, , , ,

百度一下,你就知道]

"""

print(content[0])

#

text = head.get_text() # 獲取head標(biāo)簽內(nèi)部的文字

# 百度一下,你就知道

print(type(head.title.string)) # bs4.element.NavigableString

if type(head.title.string)== bs4.element.NavigableString: # 過(guò)濾注釋內(nèi)容

print('這是注釋內(nèi)容')

else:

print('這不是注釋')

獲取子孫節(jié)點(diǎn)(tpye:generator)

descendants = soup.p.descendants

find&&find_all查找

find_all( name , attrs , recursive , text , **kwargs )

soup.find('a')

soup.find('a',title='hhh')

soup.find('a',id='',class_='')

soup.find_all('a') # 查找所有標(biāo)簽

soup.find(id=True) # 查找所有包含id屬性的標(biāo)簽

soup.find_all(limit=2) # 限定查找的返回?cái)?shù)量

soup.find_all(['a','p']) # 查找所有標(biāo)簽和標(biāo)簽

str(soup.find_all('a',class_='title')[0]) # 注意因?yàn)閏lass為關(guān)鍵字,所以用'class_'代替

soup.find_all(attrs = {'data-role':'goto-input'}) # '-'不能直接用作屬性名,需用字典括起來(lái)

select選擇(type:list)

soup.select('.main > ul > li > a')[0].string

總結(jié)

以上是生活随笔為你收集整理的bpython bs4用哪个解释器好_针对python爬虫bs4(BeautifulSoup)库的基础问题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。