mas*_*bro 8 html python beautifulsoup web-scraping
<span>
I Like
<span class='unwanted'> to punch </span>
your face
</span>
Run Code Online (Sandbox Code Playgroud)
如何打印"我喜欢你的脸"而不是"我喜欢打你的脸"
我试过这个
lala = soup.find_all('span')
for p in lala:
if not p.find(class_='unwanted'):
print p.text
Run Code Online (Sandbox Code Playgroud)
但它给出了"TypeError:find()不带关键字参数"
您可以extract()在获取文本之前删除不需要的标记.
但它保留了所有'\n',spaces所以你需要一些工作来删除它们.
data = '''<span>
I Like
<span class='unwanted'> to punch </span>
your face
<span>'''
from bs4 import BeautifulSoup as BS
soup = BS(data, 'html.parser')
external_span = soup.find('span')
print("1 HTML:", external_span)
print("1 TEXT:", external_span.text.strip())
unwanted = external_span.find('span')
unwanted.extract()
print("2 HTML:", external_span)
print("2 TEXT:", external_span.text.strip())
Run Code Online (Sandbox Code Playgroud)
结果
1 HTML: <span>
I Like
<span class="unwanted"> to punch </span>
your face
<span></span></span>
1 TEXT: I Like
to punch
your face
2 HTML: <span>
I Like
your face
<span></span></span>
2 TEXT: I Like
your face
Run Code Online (Sandbox Code Playgroud)
您可以跳过Tag外部范围内的每个对象并仅保留NavigableString对象(它是HTML中的纯文本).
data = '''<span>
I Like
<span class='unwanted'> to punch </span>
your face
<span>'''
from bs4 import BeautifulSoup as BS
import bs4
soup = BS(data, 'html.parser')
external_span = soup.find('span')
text = []
for x in external_span:
if isinstance(x, bs4.element.NavigableString):
text.append(x.strip())
print(" ".join(text))
Run Code Online (Sandbox Code Playgroud)
结果
I Like your face
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9505 次 |
| 最近记录: |