要讀取HTML 檔案中的文字內容,請執行下列步驟:載入HTML 檔案解析HTML使用text 屬性或get_text() 方法來擷取文字可選:清理文字(刪除空白、特殊字元和轉換小寫)輸出文字(列印、寫入檔案等)
#如何讀取HTML 檔案中的文字內容
#若要從HTML 檔案中擷取文字內容,可以使用下列步驟:
1.載入HTML 檔案
import requests url = 'https://example.com' response = requests.get(url)
2.解析HTML
from bs4 import BeautifulSoup soup = BeautifulSoup(response.text, 'html.parser')
3. 提取文字內容
有兩種方法可以提取文字內容:
text = soup.text
text = soup.get_text()
#如果需要進一步清理文字內容,可以執行以下操作:
text = text.replace(' ', '')
import string text = text.translate(str.maketrans('', '', string.punctuation))
text = text.lower()
print(text)
with open('output.txt', 'w') as f: f.write(text)
以上是如何讀取html檔案中的文字內容的詳細內容。更多資訊請關注PHP中文網其他相關文章!