from bs4 import BeautifulSoup html_doc = """ <html><head><title>The Dormouse's story</title></head> cover: /img/post-cover/31.jpg <body> <p class="title"><b>The Dormouse's story</b></p> cover: /img/post-cover/31.jpg <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',form_encoding='utf-8') # print(Soup.prettify()) print(Soup.title) # <title>The Dormouse's story</title> print(Soup.title.name) # title print(Soup.title.string) # The Dormouse's story
print(Soup.p['class']) # ['title']
print(Soup.a) # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> print(Soup.find('a')) # <a class="sister" href="http://example.com/elsie" id="link1">Elsie</a> print(Soup.find_all('a')) # [<a class="sister" href="http://example.com/elsie" id="link1">Elsie</a>, # <a class="sister" href="http://example.com/lacie" id="link2">Lacie</a>, # <a class="sister" href="http://example.com/tillie" id="link3">Tillie</a>] print(Soup.get_text()) # 获取所有文字内容 ''' The Dormouse's story The Dormouse's story Once upon a time there were three little sisters; and their names were Elsie, Lacie and Tillie; and they lived at the bottom of a well. ... '''