Python學習爬蟲(3)——BeautifulSoup入門介紹

作者:IT小樣
beautifulsoup 可以從HTML或者XML文件中提取數據。

BeautifulSoup基礎引用

html_doc = '''
<html><head><title>hello,tester</title></head><body>
<p class="title"><b><h1>Hello,welcome</h1></b></p>
<p class="documentation">Tester, welcome! This is a new partion of your job's life. With python, you can finnish your work easier and faster.How, <a href="http://example.com/easier" class="easier" id="link1"> easier </a> and <a href="http://example.com/faster" class="faster" id = "link2">faster</a> Now, you have a initial impression about python.</p>
<p class="documention">let's go!!!</p> 
</body></html>
'''

上面是一段html代碼,可以用這段代碼來初步瞭解BeautifulSoup。

from bs4 import BeautifulSoup

soup = BeautifulSoup(html_doc)
print("html_doc:"soup.prettify())
print("title:"soup.title)
print(soup.title.name)
print(soup.title.string)
print(soup.title.parent.name)
print(soup.p)
print(soup.p['class'])
print(soup.a)
print(soup.find_all('a'))
print(soup.find(id="link2"))
for link in soup.find_all('a'):
    print(link.get('href'))
print(soup.get_text())

依次對代碼進行解析:soup=BeautifulSoup(html_doc),將html_doc轉化爲BeautifulSoup對象
soup.prettify(),將html_doc文檔規範化輸出
soup.title,輸出整個title塊,如圖:
soup.title
soup.title.name,輸出title的名稱
soup.title.name
soup.title.string,輸出title的內容
soup.title.string
soup.title.parent.name,輸出title的上一層的名稱
soup.title.parent.name
soup.p,輸出段落p的整個內容,顯示文檔中找到的第一個
soup.p
soup.p[‘class’],輸出找到的p的內容的class屬性內容:
soup.p['class']
soup.a,輸出找到的第一個
soup.a

soup.find_all(‘a’),以列表形式輸出找到的所有
soup.find_all('a')

soup.find(id=‘link2’),輸出id=‘link2’的元素
soup.find(id='link2')
for link in soup.find_all(‘a’)
print(link.get(‘href’))
這一個for語句,是找到所有的a元素,並且分別輸出每一個的href的內容
link.get('href')

soup.get_text(),獲取文檔中所有的文字內容
soup.get_text()
以上是初步的BeautifulSoup的入門指導

上一篇:Python學習爬蟲(2)–requests庫
下一篇:Python學習爬蟲(4)–beautifulSoup庫Tag對象和NavigableString詳細介紹

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章