【问题标题】:Is it possible to extract the text between the <p> tags in a html document?是否可以提取 html 文档中 <p> 标签之间的文本?
【发布时间】:2020-02-24 20:19:06
【问题描述】:

我正在使用 BeautifulSoup 从 html 文件中提取内容。 我有几千个提取的 html 文件,并且想要提取所有文件中 p 标签之间的内容。 以下是相关代码:

for line in text:
    soup = bs(line, 'html.parser')
    autor = soup.find_all('p').text
    s = autor.replace('\\n', '')
    l.append(s)

我想使用 find_all().text 来提取所有 p 标签之间的文本,但是我收到了这个错误:

ResultSet 对象没有“文本”属性。您可能将项目列表视为单个项目。当你打算调用 find() 时,你调用了 find_all() 吗?

如果我只使用 find().text

autor = soup.find('p').text

我只是得到每个文件的第一个 p 标签。

有人可以帮忙吗?

【问题讨论】:

标签: python beautifulsoup


【解决方案1】:

文本自然用换行符分隔:

paragraph_text = '\n\n'.join(p.text for p in soup.find_all('p'))

或者,例如,如果您想用空格连接段落:

paragraph_text = ' '.join(p.text for p in soup.find_all('p'))

&lt;p&gt;中所有文字的列表:

paragraphs = [p.text for p in soup.find_all('p')]

【讨论】:

    猜你喜欢
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-22
    • 2016-09-10
    • 2019-09-04
    • 2021-08-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多