Beautifulsoup4-使用find()提取文本的正确方法是什么? [英] Beautifulsoup4 - What is the correct way to extract text using find()?

查看:56
本文介绍了Beautifulsoup4-使用find()提取文本的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用BS4解析网站,并希望从其源代码中打印文本"+26.67%"

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>

我一直在弄弄 .find_all()命令(

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?

我的代码:

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)

推荐答案

一个小例子:

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

查找返回第一个 Tag find_all 返回 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%

如果要在 b font 下使用指定的 nobr ,则可以是:

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

如果先前的 .find 返回无,则

连续的 .find 可能会导致异常,请注意.

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

这篇关于Beautifulsoup4-使用find()提取文本的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆