这是我的代码的输出
<h1 class="it-ttl" id="itemTitle" itemprop="name"><span class="g-hdn">Details about </span>item name goes here</h1>
我只想获取项目名称,没有“详细信息”部分。
我的 Python 代码选择了特定的 div id 是
for content in soup.select('#itemTitle'):
print(content.text)
请您参考如下方法:
您可以使用 decompose() clear()或 extract() . 根据文档:
Tag.decompose() removes a tag from the tree, then completely destroys it and its contents
Tag.clear() removes the contents of a tag
PageElement.extract() removes a tag or string from the tree. It returns the tag or string that was extracted
from bs4 import BeautifulSoup
html = '''<h1 class="it-ttl" id="itemTitle" itemprop="name"><span class="g-hdn">Details about </span>item name goes here</h1>'''
soup = BeautifulSoup(html, 'lxml')
for content in soup.select('#itemTitle'):
content.span.decompose()
print(content.text)
输出:
item name goes here
