2015-12-17 31 views
1

我目前在使用BeautifulSoup時遇到了一些麻煩,並且想知道是否有解決方法,因爲我並不確定如何搜索此問題。Python; BeautifulSoup和內置函數

我目前通過使用BeautifulSoup模塊和Python解析電子郵件中的數據。你能做到以下幾點:

>>> soup.title.string 
>>> 'The string found withing the Title Tags' 

不過,目前的問題是,我想提取<from>標籤之間的信息。

因此,鍵入以下時:

>>> soup.from.string 

Python的認識from作爲一個內置的功能,因此,我無法得到這個工作。有沒有辦法讓Python從模塊的功能中識別出來,而不是它自己的內置函數?

回答

1

在這種情況下,您應該使用soup.find(tagName)。例如,from標籤:

soup.find('from').string 

如果您在HTML文件中有更多的from標籤,soup.find_all()會是一個更好的選擇。當你在搜索from,等它返回所有from標籤的列表:

soup.find_all('from')[2].string # get the string in the third `from` tag 

我們也有soup.find_next()soup.find_parents()。要了解它們的用法,請檢查我鏈接的文檔。


下面是關於他們一個簡單的演示:

>>> from bs4 import BeautifulSoup 
>>> soup = BeautifulSoup(""" 
... <html> 
...  <head> 
...  </head> 
...  <body> 
...   <from>The first `from` tag</from> 
...   <from>The second `from` tag</from> 
...   <from>The third `from` tag</from> 
...  </body> 
... </html>""", "html.parser") 

>>> soup.find('from').string 
'The first `from` tag' 

>>> soup.find_all('from') 
[<from>The first `from` tag</from>, 
<from>The second `from` tag</from>, 
<from>The third `from` tag</from>] 

>>> soup.find_all('from')[2].string 
'The third `from` tag' 
>>> 
+0

@DeanHenry:如果你認爲我的這個答案是有幫助的,請接受它。查看我們的[旅遊]瞭解更多詳情。 –