【问题标题】:Finding a specific string in a page with Beautifilsoup使用 Beautifulsoup 在页面中查找特定字符串
【发布时间】:2016-04-13 21:23:27
【问题描述】:

我正在使用 bs4,并希望从文档中返回特定内置 Python 函数的描述,例如从这个页面获取 abs():

https://docs.python.org/2/library/functions.html

会返回这个:

绝对 (x)

返回一个数字的绝对值。参数可以是普通整数或长整数或浮点数。如果参数是复数,则返回其大小。

除了<p> 元素以及如何仅获取<p> 元素及其在其中的文本之外,我一直在寻找我应该寻找的东西。我知道我可以进行findAll 搜索,但我想这样做而不使用页面中的文本(例如,好像用户事先不知道文本是什么):

import requests, bs4, re

res = requests.get('https://docs.python.org/2/library/functions.html')
res.raise_for_status()
abs_soup = bs4.BeautifulSoup(res.text)
abs_elems = abs_soup.body.findAll(text=re.compile('^abs$'))
print abs_elems
abs_desc = abs_soup.select   # this is the part Im stuck on
print abs_desc

【问题讨论】:

    标签: python regex bs4


    【解决方案1】:

    嗯,Python的文档把所有函数都放在<dl class="function">里面,里面还有一个<dt id="name_of_the_function">

    所以我建议只使用:

    import requests
    from bs4 import BeautifulSoup
    
    res = requests.get('https://docs.python.org/2/library/functions.html')
    abs_soup = BeautifulSoup(res.text, "html.parser")
    
    print(abs_soup.find('dt', {'id': 'abs'}).find_next('dd').text)
    

    输出:

    返回一个数字的绝对值。论点可以是简单的或冗长的 整数或浮点数。如果参数是复数,它的 返回幅度。

    首先,我们使用abs_soup.find('dt', {'id': 'abs'}) 来找到abs<dt> 标签,因为它是id,然后我们使用.find_next('dd') 来获取<dd> 标签之后的下一个<dd> 标签。

    最后,使用.text 来获取<dd> 标签的文本,但是你也可以使用.find_next('p').text) 代替,输出是一样的。

    【讨论】:

      【解决方案2】:

      我愿意,

      >>> func = abs_soup.select('dl.function')
      >>> for i in func:
          if i.select('dt#abs'):
              print 'abs\n'
              print i.select('dd')[0].text
      
      
      abs
      
      Return the absolute value of a number.  The argument may be a plain or long
      integer or a floating point number.  If the argument is a complex number, its
      magnitude is returned.
      
      >>> 
      

      用这个替换我代码的最后两行..

          print i.find('dt').text
          print i.find('dd').text
      

      【讨论】:

        猜你喜欢
        • 2019-03-17
        • 2015-03-23
        • 2013-07-14
        • 2023-03-15
        • 1970-01-01
        • 2023-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多