日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python爬虫提取a标签_Python爬虫库BeautifulSoup获取对象(标签)名,属性,内容,注释

發布時間:2024/8/1 python 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python爬虫提取a标签_Python爬虫库BeautifulSoup获取对象(标签)名,属性,内容,注释 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

一、Tag(標簽)對象

1.Tag對象與XML或HTML原生文檔中的tag相同。

from bs4 import BeautifulSoup

soup = BeautifulSoup('Extremely bold','lxml')

tag = soup.b

type(tag)

bs4.element.Tag

2.Tag的Name屬性

每個tag都有自己的名字,通過.name來獲取

tag.name

'b'

tag.name = "blockquote" # 對原始文檔進行修改

tag

Extremely bold

3.Tag的Attributes屬性

獲取單個屬性

tag['class']

['boldest']

按字典的方式獲取全部屬性

tag.attrs

{'class': ['boldest']}

添加屬性

tag['class'] = 'verybold'

tag['id'] = 1

print(tag)

Extremely bold

刪除屬性

del tag['class']

del tag['id']

tag

Extremely bold

4.Tag的多值屬性

多值屬性會返回一個列表

css_soup = BeautifulSoup('

','lxml')

print(css_soup.p['class'])

['body', 'strikeout']

rel_soup = BeautifulSoup('

Back to the homepage

','lxml')

print(rel_soup.a['rel'])

rel_soup.a['rel'] = ['index', 'contents']

print(rel_soup.p)

['index']

Back to the homepage

如果轉換的文檔是XML格式,那么tag中不包含多值屬性

xml_soup = BeautifulSoup('

', 'xml')

xml_soup.p['class']

'body strikeout'

二、可遍歷字符串(NavigableString)

1.字符串常被包含在tag內,使用NavigableString類來包裝tag中的字符串

from bs4 import BeautifulSoup

soup = BeautifulSoup('Extremely bold','lxml')

tag = soup.b

print(tag.string)

print(type(tag.string))

Extremely bold

2.一個 NavigableString 字符串與Python中的str字符串相同,通過str() 方法可以直接將 NavigableString 對象轉換成str字符串

unicode_string = str(tag.string)

print(unicode_string)

print(type(unicode_string))

Extremely bold

3.tag中包含的字符串不能編輯,但是可以被替換成其它的字符串,用 replace_with() 方法

tag.string.replace_with("No longer bold")

tag

No longer bold

三、BeautifulSoup對象 BeautifulSoup 對象表示的是一個文檔的全部內容。

大部分時候,可以把它當作 Tag 對象,它支持 遍歷文檔樹 和 搜索文檔樹 中描述的大部分的方法。

四、注釋與特殊字符串(Comment)對象

markup = ""

soup = BeautifulSoup(markup,'lxml')

comment = soup.b.string

type(comment)

bs4.element.Comment

Comment 對象是一個特殊類型的 NavigableString 對象

comment

'Hey, buddy. Want to buy a used parser?'

更多關于Python爬蟲庫BeautifulSoup的使用方法請查看下面的相關鏈接

本文標題: Python爬蟲庫BeautifulSoup獲取對象(標簽)名,屬性,內容,注釋

本文地址: http://www.cppcns.com/jiaoben/python/299134.html

總結

以上是生活随笔為你收集整理的python爬虫提取a标签_Python爬虫库BeautifulSoup获取对象(标签)名,属性,内容,注释的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。