我想用Python HTMLParser解析一個網頁。我想獲取標籤的內容,但我不知道如何去做。這是我到目前爲止的代碼:Python和HTMLParser.handle_data() - 如何從標籤獲取數據?
import urllib.request
from html.parser import HTMLParser
class MyHTMLParser(HTMLParser):
def handle_data(self, data):
print("Encountered some data:", data)
url = "website"
page = urllib.request.urlopen(url).read()
parser = MyHTMLParser(strict=False)
parser.feed(str(page))
如果我理解正確的話,我可以使用handle_data()
函數來獲取標籤之間的數據。如何指定從哪個標籤獲取數據?我如何獲取數據?
我建議你使用[BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/),因爲它有一個非常友好的界面。 – jcollado
不僅僅是因爲友好的界面,它更容易理解HTML格式的錯誤/不正確的HTML格式,你會在狂放的網頁上看到它。 – babbageclunk
我試過BeautifulSoup。我解析的頁面使它窒息。即使BeautifulSoup不起作用,你怎麼做? :) – user1049697