beautifulsoup4, correct way to use .find_all?

守給你的承諾、 提交于 2019-12-12 04:39:09

问题


If I parse a website using BS4, and from its source code i want to print the text "+26.67%"

 <font color="green"><b><nobr>+26.67%</nobr></b></font>

I have been messing around with the .find_all() command (http://www.crummy.com/software/BeautifulSoup/bs4/doc/) to no avail. What would be the correct way to search the source code and print just the text?

my code:

import requests
from bs4 import BeautifulSoup

    set_url = "*insert web address here*"
    set_response = requests.get(set_url)
    set_data = set_response.text
    soup = BeautifulSoup(set_data)
    e = soup.find("nobr")
    print(e.text)

回答1:


A small example:

>>> 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%'

find return the first Tag, find_all return a ResultSet:

>>> type(e)
<class 'bs4.element.Tag'>
>>> es = soup.find_all("nobr")
>>> type(es)
<class 'bs4.element.ResultSet'>
>>> for e in es:
...     print e.get_text()
...
+26.67%

If you want the specified nobr under b and font, it can be:

>>> soup.find("font",{'color':'green'}).find("b").find("nobr").get_text()
u'+26.67%'

Continuous .find may cause an exception if prior .find returns None, pay attention.




回答2:


Use a CSS selector:

>>> 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>]

Add or remove properties or element names form the selector string to make the match more or less precise.




回答3:


Here you have my solution

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


来源:https://stackoverflow.com/questions/21750979/beautifulsoup4-correct-way-to-use-find-all

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!