【问题标题】:What should I do if a class name is present in another class name?如果一个类名出现在另一个类名中怎么办?
【发布时间】:2020-03-08 02:08:11
【问题描述】:

我试图从电子商务网站上抓取一些数据,我需要类名称为“VGWI6T”的 div 标签内的 span 标签中产品的折扣百分比,但它也给了我这些产品的折扣百分比类名“VGWI6T _2YXy_Y”。

<div>
.......
.......
......
<div class= "VGWI6T">

  <span>25% off</span>

</div>
.....
.....
.....
</div>

.........
...........
......

<div>
....
....
....
<div class= "VGWI6T _2YXy_Y">

  <span>25% off</span>
</div>
....
.....
</div>

我如何才能仅获取具有前类名称(VGWI6T)的那些产品? 当我在做的时候:

Discount = bs.find_all('div',class_='VGWI6T', attars= 'span')

它给了我所有的产品折扣,即使它们属于 VGWI6T _2YXy_Y 类。

【问题讨论】:

    标签: python-3.x beautifulsoup python-requests python-beautifultable


    【解决方案1】:

    使用 css 选择器且类不包含 _2YXy_Y

    from bs4 import BeautifulSoup
    html='''<div>
    .......
    .......
    ......
    <div class= "VGWI6T">
    
      <span>25% off</span>
    
    </div>
    .....
    .....
    .....
    </div>
    
    .........
    ...........
    ......
    
    <div>
    ....
    ....
    ....
    <div class= "VGWI6T _2YXy_Y">
    
      <span>25% off</span>
    </div>
    ....
    .....
    </div>'''
    
    soup=BeautifulSoup(html,"html.parser")
    for item in soup.select(".VGWI6T:not(._2YXy_Y) span "):
        print(item.text)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-08-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-15
      相关资源
      最近更新 更多