首页 > 解决方案 > 打开文件并从 html Python 中提取文本的函数

问题描述

我对 Python 很陌生,我正在尝试编写一个程序来提取 html 标签(不带标签)中的文本并将其写入不同的文本文件以供将来分析。我也提到了这个这个。我来了能够得到下面的代码。但是我怎么能把它写成一个单独的函数呢?就像是

"def read_list('file1.txt')

然后做同样的刮?我问的原因是此代码的输出(op1.txt)将用于词干提取,然后用于其他计算。此代码的输出也没有按预期逐行编写。非常感谢您的任何意见!

f = open('file1.txt', 'r')
for line in f:
    url = line
    html = urlopen(url)
    bs = BeautifulSoup(html, "html.parser")
    content = bs.find_all(['title','h1', 'h2','h3','h4','h5','h6','p'])

    with open('op1.txt', 'w', encoding='utf-8') as file:
        file.write(f'{content}\n\n')
        file.close()

标签: pythonhtmlweb-scrapingbeautifulsoupwrite

解决方案


像这样试试

from urllib.request import urlopen
from bs4 import BeautifulSoup

def read_list(fl):
    with open(fl, 'r') as f:
        for line in f:
            html = urlopen(line.strip()).read().decode("utf8")
            bs = BeautifulSoup(html, "html.parser")
            content = '\n'.join([x.text for x in bs.find_all(['title','p']+[f'h{n}' for n in range(1,7)])])
        
    with open('op1.txt', 'w', encoding='utf-8') as file:
        file.write(f'{content}\n\n')

推荐阅读