Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Beautifulsoup4-使用find()提取文本的正确方法是什么?_Python_Html_Parsing_Beautifulsoup_Findall - Fatal编程技术网

Python Beautifulsoup4-使用find()提取文本的正确方法是什么?

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&

如果我使用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></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%