【问题标题】:How can I scrape span with no unique identifier?如何在没有唯一标识符的情况下抓取 span?
【发布时间】:2021-05-29 14:40:36
【问题描述】:

PYTHON-beautifulsoup:

选择后: divtotals = soup.find(id="od-subtotals")

我把这个烂摊子和多个同一个班级弄得一团糟。我想选择最后一个有 $6.48 的跨度

<div id="od-subtotals" class="a-fixed-right-grid-col a-col-right" style="width:260px;margin-right:-260px;float:left;">
        
    <div class="a-row">
        <div class="a-column a-span7 a-text-left">
                <span class="a-color-base">
                    Item(s) Subtotal: 
                </span> 
        </div> 

        <div class="a-column a-span5 a-text-right a-span-last">
            <span class="a-color-base">
                $5.99
            </span> 
        </div> 
    </div> 

    
            
    <div class="a-row a-spacing-mini">
    </div>  
    <div class="a-row">
        <div class="a-column a-span7 a-text-left">
                <span class="a-color-base">
                    Total before tax:
                </span> 
        </div> 
        <div class="a-column a-span5 a-text-right a-span-last">
            <span class="a-color-base">
                $5.99
            </span> 
        </div> 
    </div> 
    

            
    <div class="a-row a-spacing-mini">
    </div>         
    <div class="a-row">
        <div class="a-column a-span7 a-text-left">
            <span class="a-color-base a-text-bold">
                Grand Total:
            </span> 
        </div> 
        <div class="a-column a-span5 a-text-right a-span-last">
            <span class="a-color-base a-text-bold">
                $6.48  <!-- return this value -->
            </span> 
        </div> 
    </div> 
    
</div>

对不起,我是新手,我正在写这篇文章,因为 stackoverflow 不允许我发布显示错误看起来你的帖子主要是代码;请添加更多细节。我希望这是足够的细节

【问题讨论】:

  • 到目前为止,您从 SO 中尝试过什么以获得简单的输出提示:您正在找到带有 id 的 div 标签,因此请在 find 方法中提及所有内容,例如 tag-nameattrs 参数
  • id= od-subtotals 是我找到的最后一个唯一标识符。我选择了它,但留下了多个具有相同类的 div 和 span。我想选择最后一个跨度并返回文本。

标签: python selenium beautifulsoup selenium-chromedriver


【解决方案1】:
  1. 我已将您的数据作为 html,所以如果数据不是动态加载的并且 div 是可见的 可以试试办法

  2. 在哪里找到所有带有 a-column 的 div,这些 div 作为 6 个标签的列表返回,最后一个标签包含 你的信息,所以使用 find 和 span 方法来获取你的输出

from bs4 import BeautifulSoup
soup=BeautifulSoup(html,"html.parser")
soup.find_all("div",attrs={"class":"a-column"})[5].find("span").get_text(strip=True)

输出:

'$6.48'

【讨论】:

  • 在进行最终测试时,我注意到页面是动态加载的,并且在 od-subtotals div 中有更多 div。我想如果我在包含 Grand Total 的跨度之后选择下一个跨度:文本每次都会给我正确的结果。你能告诉我怎么做吗
  • 如果可以的话,能否提供url链接,这样会更好理解!
  • 需要登录才能查看页面。我不认为我可以分享链接。我编辑了我的上一条评论,你能检查它是否有意义
  • 好吧,我可以建议你从这个post 尝试一下,可能会奏效!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
  • 2019-03-26
  • 1970-01-01
  • 2020-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多