【发布时间】:2021-12-31 02:13:01
【问题描述】:
我正在尝试抓取我放入本地 html 文件的网站。当我使用 find_all() 方法时,我可以在 python 结果中显示所有标签的文本。问题是我无法让它显示 .txt 文件中的所有文本。
from bs4 import BeautifulSoup
def interest_retrieval(文件名): 使用 open(f'{filename}', 'r') 作为 html_file: 内容 = html_file.read()
soup = BeautifulSoup(content, 'lxml')
interests = soup.find_all('h2')
for interest in interests:
with open ('interest.txt', 'w') as file:
file.write(f'{interest.text}')
print(interest.text)
Python 会将所有标签显示为文本,但当我写入 .txt 文件时,它只会显示最后一个标签。 output of txt document
编辑 我也想做类似的事情,但使用 docx 文件。我采用了 Igor 建议的代码,但将部分更改为我需要的 docx 文件。但我仍然对 docx 文件有同样的问题。
from bs4 import BeautifulSoup
import docx
def interest_retrieval(filename):
with open(f'{filename}', 'r') as html_file:
content = html_file.read()
soup = BeautifulSoup(content, 'lxml')
interests = soup.find_all('h2')
with open('interest.txt', 'w') as file:
for interest in interests:
mydoc = docx.Document()
mydoc.add_paragraph(f'{interest.text}')
mydoc.save("C:/Users\satam\PycharmProjects\pythonProject\Web Scraper\list.docx")
print(interest.text)
【问题讨论】:
标签: python web-scraping beautifulsoup