# -*- coding: utf-8 -*- from bs4 import BeautifulSoup # 安裝:pip install beautifulsoup4 # Beautiful Soup支持Python標準庫中的HTML解析器,還支持一些第三方的解析器,其中一個是 lxml .根據操做系統不一樣,能夠選擇下列方法來安裝lxml: # 安裝解析器:pip install lxml # 另外一個可供選擇的解析器是純Python實現的 html5lib , html5lib的解析方式與瀏覽器相同,能夠選擇下列方法來安裝html5lib: # 安裝解析器:pip install html5lib # 基本使用:直接鏈接網頁太麻煩,直接拿下載好的網頁作測試; # html_doc = """ # <html><head><title>The Dormouse's story</title></head> # <body> # <p class="title"><b>The Dormouse's story</b></p> # <p class="title"><b>The Dormouse's story2</b></p> # # <p class="story">Once upon a time there were three little sisters; and their names were # <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, # <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and # <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; # and they lived at the bottom of a well.</p> # # <p class="story">...</p> # """ # 基本使用:容錯處理,文檔的容錯能力指的是在HTML代碼不完整的狀況下,使用該模塊能夠識別錯誤 # 使用該Beautifulsoup解析上述代碼,可以獲得一個bearutifulsoup對象,而且按照標準格式輸出 # soup = BeautifulSoup(html_doc,"lxml") # 具備容錯功能 # print(soup.prettify()) #能夠處理好縮進,按照標準格式輸出 # soup = BeautifulSoup(html_doc,"html.parser") # print(soup) # 遍歷文檔樹 # 一、用法 # soup = BeautifulSoup(open("a.html"),"lxml") # soup = BeautifulSoup(html_doc,"lxml") # print(soup.p) #存在多個相同的標籤只返回第一個 # print(soup.a) # 二、獲取標籤的名稱 # print(soup.p.name) #獲取該標籤的名稱,不過有點畫蛇添足 # 三、獲取標籤屬性 # print(soup.p.attrs) # 四、獲取標籤的內容 # print(soup.p.string) # p下邊沒有子元素的時候返回他的文本,不然返回none # print(soup.p.strings) # 拿到p的生成器對象 # print(soup.p.text) #去文本內容 # for line in soup.stripped_strings: # print(line) # 去掉空白,打印p的文本內容 # 五、嵌套選擇: # print(soup.head.title.string) #標籤嵌套 # print(soup.body.a.string) # 六、子節點,子孫接點 # print(soup.p.contents) #取p下邊的全部子節點 # print(soup.p.children) #獲得一個迭代器,包含p下的全部子節點 # for i in soup.p.children: # print(i) # for i,child in enumerate(soup.p.children): # print(i,child) # print(soup.p.descendants) # for i,child in enumerate(soup.p.descendants): # print(i,child) # 獲取子孫接點 # 七、父節點,祖先接點 # print(soup.a.parent) #獲取a的父節點 # print(list(soup.a.parents)) #獲取到a的全部祖先元素、 # 八、兄弟接點 # print(soup.a.next_sibling) #h獲取a的上一個兄弟 # print(soup.a.previous_sibling) # h獲取a的下一個兄弟 # print(list(soup.a.next_siblings)) #全部的兄弟列表 # print(soup.a.previous_siblings) #兄弟的生成器對象 # 搜索文檔樹 # 五種過濾器: 字符串、正則表達式、列表、True、方法 # 一、字符串:標籤名 # print(soup.find_all("b")) # 二、正則表達式 # import re # print(soup.find_all(re.compile("^b"))) # 三、列表 # print(soup.find_all(["a","b"])) # 找到a或b # 四、True # print(soup.find_all(True)) #找到全部的tag # for tag in soup.find_all(True): # print(tag.name) #找到全部的標籤名 # 五、方法:若是沒有合適過濾器,那麼還能夠定義一個方法,方法只接受一個元素參數 ,若是這個方法返回 True 表示當前元素匹配而且被找到,若是不是則反回 False # def has_class_but_no_id(tag): # return tag.has_attr("class") and not tag.has_attr("id") # # print(soup.find_all(has_class_but_no_id)) # find_all( name , attrs , recursive , text , **kwargs ) html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p id="my p" class="title"><b id="bbb" class="boldest">The Dormouse's story</b> </p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ import re from bs4 import BeautifulSoup soup=BeautifulSoup(html_doc,'lxml') # 一、name: 搜索name參數的值可使任一類型的 過濾器 ,字符竄,正則表達式,列表,方法或是 True # print(soup.find_all(name=re.compile("^t"))) # 二、keyword: key=value的形式,value能夠是過濾器:字符串 , 正則表達式 , 列表, True . # print(soup.find_all(id=re.compile("my"))) # print(soup.find_all(href=re.compile("lacie"),id=re.compile("\d"))) # print(soup.find_all(id=True))? # # 有些tag屬性在搜索不能使用,好比HTML5中的 data-* 屬性: # data_soup = BeautifulSoup('<div data-foo="value">foo!</div>','lxml') # # data_soup.find_all(data-foo="value") #報錯:SyntaxError: keyword can't be an expression # # 可是能夠經過 find_all() 方法的 attrs 參數定義一個字典參數來搜索包含特殊屬性的tag: # print(data_soup.find_all(attrs={"data-foo": "value"})) # # [<div data-foo="value">foo!</div>] # 三、按照類名查找,注意關鍵字是class_,class_=value,value能夠是五種選擇器之一 # print(soup.find_all('a',class_='sister')) #查找類爲sister的a標籤 # print(soup.find_all('a',class_='sister ssss')) #查找類爲sister和sss的a標籤,順序錯誤也匹配不成功 # print(soup.find_all(class_=re.compile('^sis'))) #查找類爲sister的全部標籤 # 四、attrs # print(soup.find_all("p",attrs={"class":"story"})) # 五、text: 值能夠是:字符,列表,True,正則 # print(soup.find_all(text='Elsie')) # print(soup.find_all('a',text='Elsie')) # 六、limit參數:若是文檔樹很大那麼搜索會很慢.若是咱們不須要所有結果,可使用 limit 參數限制返回結果的數量.效果與SQL中的limit關鍵字相似,當搜索到的結果數量達到 limit 的限制時,就中止搜索返回結果?? # print(soup.find_all("a",limit=2)) # 七、recursive:調用tag的 find_all() 方法時,Beautiful Soup會檢索當前tag的全部子孫節點,若是隻想搜索tag的直接子節點,可使用參數 recursive=False . # print(soup.html.find_all("a")) # print(soup.find_all("a")) # print(soup.html.find_all("a",recursive=False)) # find( name , attrs , recursive , text , **kwargs ) # 和find_all相似 # html_doc = """ # <html><head><title>The Dormouse's story</title></head> # <body> # <p class="title"> # <b>The Dormouse's story</b> # Once upon a time there were three little sisters; and their names were # <a href="http://example.com/elsie" class="sister" id="link1"> # <span>Elsie</span> # </a> # <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and # <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; # <div class='panel-1'> # <ul class='list' id='list-1'> # <li class='element'>Foo</li> # <li class='element'>Bar</li> # <li class='element'>Jay</li> # </ul> # <ul class='list list-small' id='list-2'> # <li class='element'><h1 class='yyyy'>Foo</h1></li> # <li class='element xxx'>Bar</li> # <li class='element'>Jay</li> # </ul> # </div> # and they lived at the bottom of a well. # </p> # <p class="story">...</p> # """ # from bs4 import BeautifulSoup # soup=BeautifulSoup(html_doc,'lxml') # css選擇器 # 一、css選擇器 # print(soup.select(".sister span")) # print(soup.select("#link1")) # print(soup.select("#link1 span")) # print(soup.select("#list-2 .element.xxx")) # print(soup.select("#list-2")[0].select(".element")) # 二、獲取屬性 # print(soup.select("#list-2 h1")[0].attrs) # 三、獲取內容 # print(soup.select("#list-2 h1")[0].get_text())
import requests from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> <body> <p class="title"><b>The Dormouse's story</b></p> <p class="title"><b>The Dormouse's story2</b></p> <p class="story">Once upon a time there were three little sisters; and their names were <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>, <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>; and they lived at the bottom of a well.</p> <p class="story">...</p> """ soup = BeautifulSoup(html_doc,"lxml") # print(soup) #完整的HTML文檔 # print(soup.text) #全部網頁的文本信息 # print(soup.p.attrs) #獲取到第一個p的屬性值 # print(soup.find_all("p")) #獲取到全部的p標籤的標籤信息 p_s = soup.find_all("p") # for p in p_s: #循環每個p標籤 # print(p.text) #打印每一個p標籤的文本信息 # for p in p_s: # print(p.a) #打印p下邊的a標籤 # a_l = soup.find("a") # print(a_l.get("href")) #獲取到a標籤的href屬性 # a_s = soup.find_all("a",attrs={"class":"sister"}) #找到全部具備sister屬性的a標籤 # print(a_s) # a_t = soup.find_all("a",text="Elsie") #獲取到a標籤的文本是elsie的標籤 # print(a_t) # a_ls = soup.find_all("a") # for a in a_ls: # print(a.get("href")) # select_a = soup.select("#link1")[0] # print(select_a)
修改文檔樹:中文連接 css
https://www.crummy.com/software/BeautifulSoup/bs4/doc/index.zh.html#id40html