BeautifulSoup 常用方法

2022-01-22 23:22:10 字數 1214 閱讀 4199

#輸出所得標籤的『』屬性值
獲取 head裡面的第乙個meta的content值

soup.head.meta['content']

獲取第乙個span的內容

soup.span.string

獲取第乙個span的內容
soup.span.text

name屬性叫keywords 所有物件

soup.find_all(attrs=)

獲採樣式site_name所有標籤

soup.find_all(class_='site_name')

soup.find(attrs=)獲取第乙個屬性名name 值是keywords的標籤
soup.find('meta',attrs=)獲取第乙個meta標籤 name屬性是keywords的標籤

print(soup.find('meta',attrs=)['content'])獲取第乙個meta標籤name屬性值是keywords的 內容值

print(soup.find('meta',attrs=)) 獲取第乙個meta標籤 name屬性值是 不區分大小寫的keywords的標籤

soup = beautifulsoup(html,"html.parser")

meta=soup.meta//獲取meta標籤

attrslist = meta.attrs;//獲取meta標籤的所有屬性元組

print "attrslist=",attrslist;

print meta.name//獲取標籤的名字

當html為ascii或utf-8編碼時,可以不指定html字元編碼,便可正確解析html為對應的soup:

當html為其他型別編碼,比如gb2312的話,則需要指定相應的字元編碼,beautifulsoup才能正確解析出對應的soup:

htmlcharset="gb2312";

soup=beautifulsoup(resphtml, fromencoding=htmlcharset);

BeautifulSoup常用方法

1.初始化 2.查詢指定標籤 eg 要找到符合的所有標籤 p.findall div 反覆利用標籤特徵可以找到最終需要的標籤 3.直接加標籤名可以找到所有子標籤 eg 找到所有標籤 p.td 4.直接以字典形式,可以訪問標籤內對應屬性的值 eg 要找到 中href 的值 www.csdn.net p...

Beautiful Soup常用操作

1 bs4 tag.contents 將標籤轉化為list 2 soup.prettify 將soup中的內容以標籤的形式列印出來 3 呼叫tag的 find all 方法時,beautiful soup會檢索當前tag的所有子孫節點,如果只想搜尋tag的直接子節點,可以使用引數 recursive...

爬蟲 Beautifulsoup 常用筆記

soup.find返回的是乙個物件,第乙個符合條件的標籤 soup.findall返回的是乙個列表,包含所有符合條件的標籤 所以find後面可以直接接get text函式,而findall不行,只能將findall列表中的元素,單獨地去get text 例如 from urllib.request ...