Beautifulsoup4庫學習

Beautifulsoup4庫學習(原文

爬蟲


Beautiful Soup一個的英文可以從HTMLXML文件中提取數據的Python庫它能夠通過你喜歡的轉換器實現慣用的文檔導航,查找,修改文檔的方式。
參考:中文文檔


HTML演示代碼


 
  1. html_doc = """
  2. <html><head><title>The Dormouse's story</title></head>
  3. <body>
  4. <p class="title"><b>The Dormouse's story</b></p>
  5. <p class="story">Once upon a time there were three little sisters; and their names were
  6. <a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,
  7. <a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
  8. <a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;
  9. and they lived at the bottom of a well.</p>
  10. <p class="story">...</p>
  11. """

基本用法


 
  1. from bs4 import BeautifulSoup # 解析html,官方推薦寫法
  2. soup = BeautifulSoup(html_doc, 'lxml') # 以lxml解析器解析,本地導入寫法
  3. #soup = BeautifulSoup(open("index.html"))
  4. soup.prettify() # 補全html代碼,容錯。
  5. print(soup.prettify())
  6. print(soup.p) # 第一個p標籤
  7. print(soup.a)
  8. print(soup.title.string) #標題內容
  9. print(soup.title.name) # 標題的名稱
  10. print(soup.head)
  11. print(soup.p['class']) # p標籤下class屬性的值
  12. soup.find_all('a') # 找到所有a標籤
  13. soup.find(id="link3") # 找到id值是link3的標籤
  14. for link in soup.find_all('a'):
  15. print(link.get('href'))
  16. print(soup.get_text()) # 從soup中獲取文字

遍歷文檔樹


 
  1. 1tagcontent屬性可以將tag的子節點和子孫節點以**列表**的方式輸出
  2. print(soup.p.contents)
  3. print(soup.p.contents[1])
  4. 2children返回的不是一個 list,不過我們可以通過遍歷獲取所有子節點,它是一個 list 生成器對象,i是索引,child是內容。
  5. for i,child in enumenerate(soup.p.children):
  6. print(i,child)
  7. 3、通過子節點可獲得其父節點,祖先節點,以及上下兄弟節點
  8. soup.a.parent
  9. soup.a.parents
  10. soup.a.next_sliblings (下一個)
  11. soup.a.previous_sliblings (上一個)
  12. 4,尋找節點,以下幾種傳遞方式
  13. soup.find_all('a') # 找到所有a標籤
  14. print(soup.find_all("a", limit=2)) #限制搜索結果數
  15. for link in soup.find_all('a'):
  16. print(link.get('href'))
  17. soup.find_all(id='1')
  18. soup.find_all(class_='name')#關鍵字 class Python中是保留字,使用 class 做參數會導致語法錯誤,可用class_
  19. soup.find_all(text='文本')
  20. print(soup.find_all(['title','b'])) # 傳遞列表進去,匹配到同時又兩個標籤相同的標籤
  21. import re
  22. '''傳遞正則表達式'''
  23. for tag in soup.find_all(re.compile("^b")):
  24. print(tag.name)
  25. print(soup.find_all(attrs={"class":"title"}))#attrs參數,定義一個字典參數來搜索包含特殊屬性的tag
  26. 5css選擇器
  27. soup.select("title")
  28. soup.select("p:nth-of-type(3)")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章