BeautifulSoup 獲取 a標籤裏的文本內容

說明

想要獲取 a標籤裏的單詞如下所示。

在這裏插入圖片描述

代碼

from bs4 import BeautifulSoup

f = open("word.txt", "r")  # 設置文件對象
html = f.read()  # 將txt文件的所有內容讀入到字符串html中

soup = BeautifulSoup(html, 'lxml')

# 獲取a標籤裏的文本內容
for item in soup.find_all("a"):
    print(item.string)
    # 將單詞寫入five_star.txt 文件
    with open('five_star.txt', 'a', encoding='utf-8') as file:
        file.write(item.string + '\n')

f.close()  # 將文件關閉

word.txt 存放的是 a標籤所有內容(內容過多 故部分展示)
在這裏插入圖片描述


five_star.txt 輸出結果(內容過多 故部分展示)

在這裏插入圖片描述

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