說明
想要獲取 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
輸出結果(內容過多 故部分展示)