python - 使用 Beautifulsoup Python 提取没有 HTML 标签的文本

标签 python web-scraping beautifulsoup

我尝试提取这部分文本,但我不知道该怎么做,我正在本地处理几个 html 文件。

<HTML><HEAD><STYLE>SOME STYLE CODE</STYLE></HEAD><META http-equiv=Content-Type content="text/html; charset=utf-8">
<BODY>
<H1>SOME TEXT I DONT WANT</H1>
THIS TEXT IS WHICH I WANT
<H1>ANOTHER TEXT I DONT WANT</H1>
ANOTHER TEXT THAT I WANT
[.. Continues ..]
</BODY></HTML>

感谢您的帮助

编辑:我尝试过使用此代码,但有时会打印 h1 标签

import glob
from bs4 import BeautifulSoup
for file in glob.glob('Logs/Key*.html'):
    with open(file) as f:
        htmlfile = f.read()
        soup = BeautifulSoup(htmlfile, 'html.parser')
        c = soup.find('body').findAll()
        for i in c:
            print i.nextSibling

编辑2:实际上问题是html文件只有一行,所以当我尝试用这个html运行该代码时,还会打印h1标签:

from bs4 import BeautifulSoup
htmlfile = '<HTML><HEAD><STYLE>SOME STYLE CODE</STYLE></HEAD><META http-equiv=Content-Type content="text/html; charset=utf-8"><BODY><H1>SHIT</H1>WANTED<H1>SHIT</H1><H1>SHIT</H1>WANTED<H1>SHIT</H1>WANTED<H1>SHIT</H1>WANTED</BODY><HTML>'
soup = BeautifulSoup(htmlfile, 'html.parser')
c = soup.find('body').findAll()
for i in c:
    print i.nextSibling

打印:

WANTED
<h1>SHIT</h1>
WANTED
WANTED
WANTED

最佳答案

现在您可以将 HTML_TEXT 作为从废弃 URL 中获得的 html。

y = BeautifulSoup(HTML_TEXT)

c = y.find('body').findAll(text=True, recursive=False)

for i in c:
    print i

关于python - 使用 Beautifulsoup Python 提取没有 HTML 标签的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38859271/

相关文章:

Python错误: TypeError: 'NoneType' object is not callable

python - 如何处理 Beautifulsoup 递归错误(或解析错误)

java - 使用java获取网页源代码?

python - beautifulsoup 找不到类

python - 使用 Beautiful Soup 查找跨度中的部分类名

python - Windows Azure 虚拟机 : Connection Timeout to Remote MySQL Database

python - 在 Python 中设置 sax 解析器的编码

python - 如何在等待 getch 的同时运行副任务?

python - 使用 beautiful soup 抓取数据时网页表结构出现问题

python - 从文件中获取 IP 地址并计算出现次数