Python 从HTML中提取字符串
我有以下要点:Python 从HTML中提取字符串,python,beautifulsoup,Python,Beautifulsoup,我有以下要点: <div class="column4"> Unlimited Subscription<br/> Discount for Monthly <br/> Total Amount </div> 从bs4导入美化组 html_doc=“” 无限制订阅每月总金额的折扣 """ soup=BeautifulSoup(html_doc,'html.parser') soup.find(“div”).text.str
<div class="column4">
Unlimited Subscription<br/> Discount for Monthly <br/> Total Amount
</div>
从bs4导入美化组
html_doc=“”
无限制订阅
每月总金额的折扣
"""
soup=BeautifulSoup(html_doc,'html.parser')
soup.find(“div”).text.strip()
要获取单个字符串,您可以获取div
元素的子元素
,并按其类型对其进行过滤
>>> bs = bs4.BeautifulSoup(html)
>>> div = bs.find(attrs={"class":"column4"})
>>> [c.strip() for c in div.children if type(c) is bs4.element.NavigableString]
['Unlimited Subscription', 'Discount for Monthly', 'Total Amount']
或者更短,使用div.strings
(或者如果您不想string
,只使用div.strings
):
如果您希望按照上面所示的方式获得输出,则可以遵循以下内容:
from bs4 import BeautifulSoup
html_elem ="""
<div class="column4">
Unlimited Subscription<br/> Discount for Monthly <br/> Total Amount
</div>
"""
soup = BeautifulSoup(html_elem, 'lxml')
for item in soup.select(".column4"):
for data in item.select("br"):data.replace_with("\n")
print(item.text.strip())
这不是正确的方法,因为html页面可能包含多个
标记。如果看不到整个html代码,则无法回答此问题。即使在投票结果向上的答案中,作者也检查了属性,这些属性可以在许多
标签中重复。是的,我理解,但如果你看到@tobias_k的答案,他已经使用class
属性找到了精确的匹配。由于class
属性是带有标记的唯一的
,因此它是正确的。我想说的是,即使这两个目的都是为了找到标签div
如何使用逻辑来找到严格匹配的问题。非常感谢,这很有帮助。我必须更加努力学习,不要问这样的问题)
>>> bs = bs4.BeautifulSoup(html)
>>> div = bs.find(attrs={"class":"column4"})
>>> [c.strip() for c in div.children if type(c) is bs4.element.NavigableString]
['Unlimited Subscription', 'Discount for Monthly', 'Total Amount']
>>> list(div.stripped_strings)
['Unlimited Subscription', 'Discount for Monthly', 'Total Amount']
from bs4 import BeautifulSoup
html_elem ="""
<div class="column4">
Unlimited Subscription<br/> Discount for Monthly <br/> Total Amount
</div>
"""
soup = BeautifulSoup(html_elem, 'lxml')
for item in soup.select(".column4"):
for data in item.select("br"):data.replace_with("\n")
print(item.text.strip())
Unlimited Subscription
Discount for Monthly
Total Amount