1. 程式人生 > >網路爬蟲之BeautifulSoup入門(四)

網路爬蟲之BeautifulSoup入門(四)

5.帶更多引數的find方法
官方文件給出的find方法的引數如下:find( name , attrs , recursive , string , **kwargs ),總體來看和find_all方法的引數沒什麼不同,在這裡仍以示例的方法給出常見的使用方法:
兩種方法的使用大致相同,注意以下兩種寫法都可以且輸出結果一致,但顯然使用find方法更方便。

soup.find_all('title', limit=1)
# [<title>The Dormouse's story</title>]

soup.find('title')
# <title>The Dormouse's story</title>

在這裡一定要注意:find_all方法的返回值為列表,而find直接返回結果;同時在沒有找到目標時,find_all返回空的列表,而find將返回None。
6. 輸出格式及編碼
- 使用prettify方法可以將BeautifulSoup物件格式化輸出,這在大型專案內是非常有用的。當然也可以對物件的某一個tag節點使用該方法,如下:

markup = '<a href="http://example.com/">I linked to <i>example.com</i></a>'
soup = BeautifulSoup(markup)

print(soup.a.prettify())
# <a href="http://example.com/">
# I linked to # <i> # example.com # </i> # </a>

若只想得到結果字串,而不注重格式的話,可以使用str方法,如下:

str(soup.a)
#'<a href="http://example.com/">I linked to <i>example.com</i></a>'

7.get_text()
若想得到tag中包含的文字內容,可以使用get_text()方法,如下:

soup.get_text()
u'\nI linked to example.com\n'
soup.i.get_text() u'example.com'

8.實踐
給出一個實踐專案原始碼地址:網頁表格抓取
介紹:專案內爬蟲部分主要應用了get_text,find,find_all,prettify等方法,實現給定URL地址的網頁表格提取儲存、展示等。