【问题标题】:Beautifulsoup4 - What is the correct way to extract text using find()?Beautifulsoup4 - 使用 find() 提取文本的正确方法是什么?
【发布时间】:2014-02-13 10:05:10
【问题描述】:

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

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

我一直在搞乱.find_all() 命令 (http://www.crummy.com/software/BeautifulSoup/bs4/doc/) 无济于事。搜索源代码并仅打印文本的正确方法是什么?

我的代码:

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)

【问题讨论】:

    标签: python html parsing beautifulsoup findall


    【解决方案1】:

    一个小例子:

    >>> 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返回第一个Tagfind_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%
    

    如果要在bfont下指定nobr,可以是:

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

    如果之前的.find返回None,连续的.find可能会导致异常,请注意。

    【讨论】:

    • 这与我使用find_all() 的方式几乎相同,我认为问题在于解析网页的方式。在您的示例中,您在我的程序中设置s = """....""" 使用请求解析页面。我会将我的代码添加到主要问题中,让我知道您的想法
    【解决方案2】:

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

    从选择器字符串中添加或删除属性或元素名称以使匹配或多或少精确。

    【讨论】:

      【解决方案3】:

      这里有我的解决方案

      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
      

      【讨论】:

        【解决方案4】:

        您可以在不使用requests 库的情况下获取文本。以下是我对您的代码所做的编辑,它给出了您预期的结果。

        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%
        

        祝你好运!

        【讨论】:

          猜你喜欢
          • 2022-08-17
          • 1970-01-01
          • 1970-01-01
          • 2021-10-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-17
          相关资源
          最近更新 更多