Python Beautifulsoup4-使用find()提取文本的正确方法是什么?
如果我使用BS4解析一个网站,并从其源代码中打印文本“+26.67%” 一个小例子:Python Beautifulsoup4-使用find()提取文本的正确方法是什么?,python,html,parsing,beautifulsoup,findall,Python,Html,Parsing,Beautifulsoup,Findall,如果我使用BS4解析一个网站,并从其源代码中打印文本“+26.67%” 一个小例子: >>> s="""<font color="green"><b><nobr>+26.67%</nobr></b></font>""" >>> print s <font color="green"><b><nobr>+26.67%</nobr></b&
>>> s="""<font color="green"><b><nobr>+26.67%</nobr></b></font>"""
>>> print s
<font color="green"><b><nobr>+26.67%</nobr></b></font>
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(s)
>>> e = soup.find("nobr")
>>> e.text #or e.get_text()
u'+26.67%'
如果您想要在b
和font
下指定的nobr
,它可以是:
>>> soup.find("font",{'color':'green'}).find("b").find("nobr").get_text()
u'+26.67%'
连续。如果先前的,则查找可能会导致异常。查找返回无,请注意。使用:
>>s=“”+26.67%”
>>>从bs4导入BeautifulSoup
>>>汤=美汤(s)
>>>汤。选择('font[color=“green”]>b>nobr')
[+26.67%]
在选择器字符串中添加或删除属性或元素名称,使匹配更加精确。这里是我的解决方案
s = """<font color="green"><b><nobr>+26.67%</nobr></b></font>"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(s)
a = soup.select('font')
print a[0].text
s=”““+26.67%””
从bs4导入BeautifulSoup
汤=美汤(s)
a=汤。选择('font')
打印[0]。文本
您无需使用请求
库即可获取文本。下面是我对您的代码所做的编辑,它给出了您的预期结果
from bs4 import BeautifulSoup
html_snippet="""<font color="green"><b><nobr>+26.67%</nobr></b></font>"""
soup = BeautifulSoup(html_snippet)
e = soup.find("nobr")
print(e.text)
祝你好运 这与我使用find_all()
的方式几乎相同,我认为问题在于我解析网页的方式。在您的示例中,您在我的程序中的设置s=“”…”
使用请求解析页面。我将把我的代码添加到主要问题中,让我知道你的想法
>>> soup.find("font",{'color':'green'}).find("b").find("nobr").get_text()
u'+26.67%'
>>> s = """<font color="green"><b><nobr>+26.67%</nobr></b></font>"""
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(s)
>>> soup.select('font[color="green"] > b > nobr')
[<nobr>+26.67%</nobr>]
s = """<font color="green"><b><nobr>+26.67%</nobr></b></font>"""
from bs4 import BeautifulSoup
soup = BeautifulSoup(s)
a = soup.select('font')
print a[0].text
from bs4 import BeautifulSoup
html_snippet="""<font color="green"><b><nobr>+26.67%</nobr></b></font>"""
soup = BeautifulSoup(html_snippet)
e = soup.find("nobr")
print(e.text)
+26.67%