AP2*_*257 38 python beautifulsoup
我正在尝试<p>使用BeautifulSoup 从网页中的元素中删除所有内部html .有内部标签,但我不在乎,我只想获得内部文本.
例如,对于:
<p>Red</p>
<p><i>Blue</i></p>
<p>Yellow</p>
<p>Light <b>green</b></p>
Run Code Online (Sandbox Code Playgroud)
我怎样才能提取:
Red
Blue
Yellow
Light green
Run Code Online (Sandbox Code Playgroud)
我既不需.string也不.contents[0]需要.也不是.extract(),因为我不想提前指定内部标签 - 我想处理任何可能发生的事情.
BeautifulSoup中是否有'just get the visible HTML'类型的方法?
---- ------ UPDATE
在建议上,尝试:
soup = BeautifulSoup(open("test.html"))
p_tags = soup.findAll('p',text=True)
for i, p_tag in enumerate(p_tags):
print str(i) + p_tag
Run Code Online (Sandbox Code Playgroud)
但这没有帮助 - 它打印出来:
0Red
1
2Blue
3
4Yellow
5
6Light
7green
8
Run Code Online (Sandbox Code Playgroud)
tal*_*nat 67
简短回答: soup.findAll(text=True)
这已经在StackOverflow和BeautifulSoup文档中得到了解答.
更新:
澄清一下,一段代码:
>>> txt = """\
<p>Red</p>
<p><i>Blue</i></p>
<p>Yellow</p>
<p>Light <b>green</b></p>
"""
>>> import BeautifulSoup
>>> BeautifulSoup.__version__
'3.0.7a'
>>> soup = BeautifulSoup.BeautifulSoup(txt)
>>> for node in soup.findAll('p'):
print ''.join(node.findAll(text=True))
Red
Blue
Yellow
Light green
Run Code Online (Sandbox Code Playgroud)
Jay*_*mon 11
接受的答案很棒,但现在已经6岁了,所以这里是目前Beautiful Soup 4版本的答案:
>>> txt = """\
<p>Red</p>
<p><i>Blue</i></p>
<p>Yellow</p>
<p>Light <b>green</b></p>
"""
>>> from bs4 import BeautifulSoup, __version__
>>> __version__
'4.5.1'
>>> soup = BeautifulSoup(txt, "html.parser")
>>> print("".join(soup.strings))
Red
Blue
Yellow
Light green
Run Code Online (Sandbox Code Playgroud)
erd*_*din 10
我偶然发现了同样的问题,想分享这个解决方案的 2019 版本。也许它可以帮助某人。
# importing the modules
from bs4 import BeautifulSoup
from urllib.request import urlopen
# setting up your BeautifulSoup Object
webpage = urlopen("https://insertyourwebpage.com")
soup = BeautifulSoup( webpage.read(), features="lxml")
p_tags = soup.find_all('p')
for each in p_tags:
print (str(each.get_text()))
Run Code Online (Sandbox Code Playgroud)
请注意,我们首先将数组内容一一打印出来,然后调用 get_text() 方法从文本中去除标签,以便我们只打印出文本。
还:
现在你的输出应该是:
希望这可以帮助寻找更新解决方案的人。
| 归档时间: |
|
| 查看次数: |
64815 次 |
| 最近记录: |