【问题标题】:How to div element within another div element using beautifulsoup?如何使用beautifulsoup在另一个div元素中div元素?
【发布时间】:2017-06-30 06:08:50
【问题描述】:

这是示例 HTML 代码:

   <div class="cb-col cb-col-25 cb-mtch-blk"><a class="cb-font-12" href="/live-cricket-scores/16947/ind-vs-ban-only-test-bangladesh-tour-of-india-2017" target="_self" title="India v Bangladesh - Only Test">
<div class="cb-hmscg-bat-txt cb-ovr-flo ">
<div class="cb-ovr-flo cb-hmscg-tm-nm">BAN</div>
<div class="cb-ovr-flo" style="display:inline-block; width:140px">322/6 (104.0 Ovs)</div>
</div>

我想从上面解析的 html 中提取像 BAN322/6 (104.0 Ovs) 这样的文本。我就是这样-

soup = BeautifulSoup(html)
div_class = soup.findAll('div',class_='cb-col cb-col-25 cb-mtch-blk')
for each in div_class:
    #I want to get those texts from variable 'each'

我该怎么做?

【问题讨论】:

    标签: python python-3.x beautifulsoup


    【解决方案1】:

    您可以将 some css selectors 与 BeautifulSoup4 一起使用:

    >>> from bs4 import BeautifulSoup
    >>> html = ...  # the html provided in the question
    >>> soup = BeautifulSoup(html, 'lxml')
    >>> name, size = soup.select('div.cb-hmscg-bat-txt.cb-ovr-flo div')
    >>> name.text
    u'BAN'
    >>> size.text
    u'322/6 (104.0 Ovs)'
    

    【讨论】:

    • 行号4,我收到“太多值无法解包”的错误。我该怎么办?
    • @ddlj,用这个代替第 4 行怎么样:print([x.text for x in soup.select('div.cb-hmscg-bat-txt.cb-ovr-flo div')])
    • @ddlj,顺便说一句,你能分享实际的 html(或你从哪里获得 html 的 url)吗?正如您在我的回答中看到的那样,我可以使用问题中给定的 html 来获取这两个文本。
    【解决方案2】:

    each表示你提供的HTML代码,你应该去下一个div标签,获取所有使用stripped_strings的文本。

    div_class = soup.findAll('div',class_='cb-col cb-col-25 cb-mtch-blk')
    for each in div_class:
        name, size = each.div.stripped_strings
        print(name, size)
    

    出来:

    BAN 322/6 (104.0 Ovs)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-25
      相关资源
      最近更新 更多