beautifulsoup模塊html
BeautifulSoup是一個模塊,該模塊用於接收一個HTML或XML字符串,而後將其進行格式化,以後遍能夠使用他提供的方法進行快速查找指定元素,從而使得在HTML或XML中查找指定元素變得簡單。html5
安裝:python
pip install beautifulsoup4
在python自動化模塊對bs已經簡單介紹了。這裏直接看快速使用:app
import requests
from bs4 import BeautifulSoup import os response = requests.get( # get請求 url='https://www.autohome.com.cn/news/' ) response.encoding = response.apparent_encoding # 使用默認的編碼原則 soup = BeautifulSoup(response.text, features='html.parser') # 實例化soup對象的兩種參數方式 # soup = BeautifulSoup(response.text, features='lxml') # print(response.text) target = soup.find(id='auto-channel-lazyload-article') # 取指定id的對象 # obj = target.find('li') # 找到第一個li li_list = target.find_all('li') # 找到全部的li, 是一個列表,裏面是bs對象 for i in li_list: # 遍歷li的列表內對象 a = i.find('a') if a: # print(a.attrs) # {'href': '//www.autohome.com.cn/news/201807/919525.html#pvareaid=102624'} # print(a.attrs.get('href')) # txt = a.find('h3') # 本質上是對象,可是打印出來是字符串 txt = a.find('h3').txt # 提取內部字符串 print(txt) img_url = a.find('img').attrs.get('src') img_url = img_url.strip('//') # src ==> //www.autohome.com.cn/**********/***.jpg print(img_url) img_type = img_url.split('.')[-1] print(img_type) img_response = requests.get(url='http://' + img_url) # 對於img的路徑再次發送get請求 import uuid with open(os.path.join('file', str(uuid.uuid4()) + '.' + img_type), 'wb') as f: f.write(img_response.content) # 二進制文件寫入文件句柄內
此段代碼,定向的抓去了目的div的內部a標籤的資源,循環發送get請求抓去處圖片保存到了本地:ide
Beautiful Soup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,若是咱們不安裝它,則 Python 會使用 Python默認的解析器,lxml 解析器更增強大,速度更快,推薦安裝。 ui
下面是常看法析器:編碼
推薦使用lxml做爲解析器,由於效率更高. 在Python2.7.3以前的版本和Python3中3.2.2以前的版本,必須安裝lxml或html5lib, 由於那些Python版本的標準庫中內置的HTML解析方法不夠穩定.url
在快速使用中咱們添加以下代碼:
print(soup.title)
print(type(soup.title))
print(soup.head)
print(soup.p)spa
經過這種soup.標籤名 咱們就能夠得到這個標籤的內容
這裏有個問題須要注意,經過這種方式獲取標籤,若是文檔中有多個這樣的標籤,返回的結果是第一個標籤的內容,如上面咱們經過soup.p獲取p標籤,而文檔中有多個p標籤,可是隻返回了第一個p標籤內容code
使用示例:
from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> ... </body> </html> """ soup = BeautifulSoup(html_doc, features="lxml")
一、標籤名稱
tag = soup.find('a') name = tag.name # 獲取 print(name) tag.name = 'span' # 設置 print(soup)
二、標籤屬性
tag = soup.find('a') attrs = tag.attrs # 獲取 print(attrs) tag.attrs = {'ik':123} # 設置 tag.attrs['id'] = 'iiiii' # 設置 print(soup)
三、字標籤
body = soup.find('body') v = body.children
四、全部子孫標籤
body = soup.find('body') v = body.descendants
五、clear、將標籤的全部子標籤所有清空(保留標籤名)
tag = soup.find('body') tag.clear() print(soup)
六、decompose、遞歸的刪除全部標籤
body = soup.find('body') body.decompose() print(soup)
七、extract、遞歸的刪除全部的標籤,並獲取刪除的標籤對象
body = soup.find('body') v = body.extract() print(soup)
八、decode,轉換爲字符串(含當前標籤);decode_contents(不含當前標籤)
body = soup.find('body') v = body.decode() v = body.decode_contents() print(v)
九、encode,轉換爲字節(含當前標籤);encode_contents(不含當前標籤)
body = soup.find('body') v = body.encode() v = body.encode_contents() print(v)
十、find,獲取匹配的第一個標籤
tag = soup.find('a') print(tag) tag = soup.find(name='a', attrs={'class': 'sister'}, recursive=True, text='Lacie') tag = soup.find(name='a', class_='sister', recursive=True, text='Lacie') print(tag)
十一、find_all,獲取匹配的全部標籤
1 # tags = soup.find_all('a') 2 # print(tags) 3 4 # tags = soup.find_all('a',limit=1) 5 # print(tags) 6 7 # tags = soup.find_all(name='a', attrs={'class': 'sister'}, recursive=True, text='Lacie') 8 # # tags = soup.find(name='a', class_='sister', recursive=True, text='Lacie') 9 # print(tags) 10 11 12 # ####### 列表 ####### 13 # v = soup.find_all(name=['a','div']) 14 # print(v) 15 16 # v = soup.find_all(class_=['sister0', 'sister']) 17 # print(v) 18 19 # v = soup.find_all(text=['Tillie']) 20 # print(v, type(v[0])) 21 22 23 # v = soup.find_all(id=['link1','link2']) 24 # print(v) 25 26 # v = soup.find_all(href=['link1','link2']) 27 # print(v) 28 29 # ####### 正則 ####### 30 import re 31 # rep = re.compile('p') 32 # rep = re.compile('^p') 33 # v = soup.find_all(name=rep) 34 # print(v) 35 36 # rep = re.compile('sister.*') 37 # v = soup.find_all(class_=rep) 38 # print(v) 39 40 # rep = re.compile('http://www.oldboy.com/static/.*') 41 # v = soup.find_all(href=rep) 42 # print(v) 43 44 # ####### 方法篩選 ####### 45 # def func(tag): 46 # return tag.has_attr('class') and tag.has_attr('id') 47 # v = soup.find_all(name=func) 48 # print(v) 49 50 51 # ## get,獲取標籤屬性 52 # tag = soup.find('a') 53 # v = tag.get('id') 54 # print(v)
十二、has_attr,檢查標籤是否具備該屬性
tag = soup.find('a') v = tag.has_attr('id') print(v)
1三、get_text,獲取標籤內部文本內容
tag = soup.find('a') v = tag.get_text('id') print(v)
1四、index,檢查標籤在某標籤中的索引位置
tag = soup.find('body') v = tag.index(tag.find('div')) print(v) tag = soup.find('body') for i, v in enumerate(tag): print(i,v)
1五、is_empty_element,是不是空標籤(是否能夠是空)或者自閉合標籤
# 判斷是不是以下標籤:'br' , 'hr', 'input', 'img', 'meta','spacer', 'link', 'frame', 'base' tag = soup.find('br') v = tag.is_empty_element print(v)
1六、當前的關聯標籤
soup.next # 不跳過內容
soup.next_element # 只找下一個對象,標籤對象
soup.next_elements
soup.next_sibling
soup.next_siblings
tag.previous
tag.previous_element
tag.previous_elements
tag.previous_sibling
tag.previous_siblings
tag.parent
tag.parents
1七、查找某標籤的關聯標籤
tag.find_next(...) # 參數跟find、 find_all同樣 tag.find_all_next(...) tag.find_next_sibling(...) tag.find_next_siblings(...) tag.find_previous(...) tag.find_all_previous(...) tag.find_previous_sibling(...) tag.find_previous_siblings(...) tag.find_parent(...) tag.find_parents(...) # 參數同find_all
18. select,select_one, CSS選擇器
soup.select("title") soup.select("p nth-of-type(3)") soup.select("body a") soup.select("html head title") tag = soup.select("span,a") soup.select("head > title") soup.select("p > a") soup.select("p > a:nth-of-type(2)") soup.select("p > #link1") soup.select("body > a") soup.select("#link1 ~ .sister") soup.select("#link1 + .sister") soup.select(".sister") soup.select("[class~=sister]") soup.select("#link1") soup.select("a#link2") soup.select('a[href]') soup.select('a[href="http://example.com/elsie"]') soup.select('a[href^="http://example.com/"]') soup.select('a[href$="tillie"]') soup.select('a[href*=".com/el"]') from bs4.element import Tag def default_candidate_generator(tag): for child in tag.descendants: if not isinstance(child, Tag): continue if not child.has_attr('href'): continue yield child tags = soup.find('body').select("a", _candidate_generator=default_candidate_generator) print(type(tags), tags) from bs4.element import Tag def default_candidate_generator(tag): for child in tag.descendants: if not isinstance(child, Tag): continue if not child.has_attr('href'): continue yield child tags = soup.find('body').select("a", _candidate_generator=default_candidate_generator, limit=1) print(type(tags), tags)
1九、標籤的內容
tag = soup.find('span') print(tag.string) # 獲取,能夠修改 tag.string = 'new content' # 設置 print(soup) tag = soup.find('body') print(tag.string) tag.string = 'xxx' print(soup) tag = soup.find('body') v = tag.stripped_strings # 遞歸內部獲取全部標籤的文本 print(v)
20、append在當前標籤內部追加一個標籤
tag = soup.find('body') tag.append(soup.find('a')) print(soup) from bs4.element import Tag obj = Tag(name='i',attrs={'id': 'it'}) obj.string = '我是一個新來的' tag = soup.find('body') tag.append(obj) print(soup)
2一、insert在當前標籤內部指定位置插入一個標籤
from bs4.element import Tag obj = Tag(name='i', attrs={'id': 'it'}) obj.string = '我是一個新來的' tag = soup.find('body') tag.insert(2, obj) print(soup)
2二、insert_after,insert_before 在當前標籤後面或前面插入
from bs4.element import Tag obj = Tag(name='i', attrs={'id': 'it'}) obj.string = '我是一個新來的' tag = soup.find('body') # tag.insert_before(obj) tag.insert_after(obj) print(soup)
2三、replace_with 在當前標籤替換爲指定標籤
from bs4.element import Tag obj = Tag(name='i', attrs={'id': 'it'}) obj.string = '我是一個新來的' tag = soup.find('div') tag.replace_with(obj) print(soup)
2四、建立標籤之間的關係
tag = soup.find('div') a = soup.find('a') tag.setup(previous_sibling=a) print(tag.previous_sibling) # 只改關聯關係,不改變位置
2五、wrap,將指定標籤把當前標籤包裹起來
from bs4.element import Tag obj1 = Tag(name='div', attrs={'id': 'it'}) obj1.string = '我是一個新來的' tag = soup.find('a') v = tag.wrap(obj1) print(soup) tag = soup.find('a') v = tag.wrap(soup.find('p')) print(soup)
2六、unwrap,去掉當前標籤,將保留其包裹的標籤
tag = soup.find('a') v = tag.unwrap() print(soup)
總結
推薦使用lxml解析庫,必要時使用html.parser標籤選擇篩選功能弱可是速度快建議使用find()、find_all() 查詢匹配單個結果或者多個結果若是對CSS選擇器熟悉建議使用select()記住經常使用的獲取屬性和文本值的方法