【问题标题】:Check if a specific class present in HTML using beautifulsoup Python使用 beautifulsoup Python 检查 HTML 中是否存在特定类
【发布时间】:2017-04-06 10:02:51
【问题描述】:

我正在编写一个脚本,并想检查一个特定的类是否存在于 html 中。

from bs4 import BeautifulSoup
import requests

def makesoup(u):
    page=requests.get(u)
    html=BeautifulSoup(page.content,"lxml")
    return html
html=makesoup('https://www.yelp.com/biz/soco-urban-lofts-dallas')

print("3 star",html.has_attr("i-stars i-stars--large-3 rating-very-large")) #it's returning False
res = html.find('i-stars i-stars--large-3 rating-very-large")) #it's returning NONE

请指导我如何解决此问题?如果我以某种方式获得标题(标题 =“3.0 星级”),这也对我有用。控制台 HTML 截图

<div class="i-stars i-stars--large-3 rating-very-large" title="3.0 star rating">
  <img class="offscreen" height="303" src="https://s3-media1.fl.yelpcdn.com/assets/srv0/yelp_design_web/8a6fc2d74183/assets/img/stars/stars.png" width="84" alt="3.0 star rating">
    </div>

【问题讨论】:

    标签: python html web-scraping beautifulsoup


    【解决方案1】:

    has_attr 是一种检查元素是否具有您想要的 属性 的方法。 class 是一个属性,i-stars i-stars--large-3 rating-very-large 是它的

    find 需要 CSS selectors,而不是类值。所以你应该改用html.find('div.i-stars.i-stars--large-3.rating-very-large')。这是因为您正在寻找具有所有这些类的div

    【讨论】:

    • 仍然返回无。
    • 请尝试find_all 而不是find,并告诉我这种行为是否仍然存在。
    • 它使用 find_all 返回空列表
    • 这只能意味着这个元素没有我们认为的这些类。可能其中一个拼写错误,或者请求中的 HTML 文件有问题?
    • 我附上了一张截图,在打印 html 时我在那里找到“i-stars i-stars--large-3 rating-very-large”,但为什么 find 功能没有得到它? :(
    【解决方案2】:

    在获取确切的课程时遇到了类似的问题。它们可以作为字典对象返回,如下所示。

    html = '<div class="i-stars i-stars--large-3 rating-very-large" title="3.0 star rating">'
    soup = BeautifulSoup(html, 'html.parser')
    find = soup.div
    classes = find.attrs['class']
    c1 = find.attrs['class'][0]
    print (classes, c1)
    

    【讨论】:

      【解决方案3】:
      from bs4 import BeautifulSoup
      import requests
      
      def makesoup(u):
          page=requests.get(u)
          html=BeautifulSoup(page.content,"lxml")
          return html
      html=makesoup('https://www.yelp.com/biz/soco-urban-lofts-dallas')
      res = html.find(class_='i-stars i-stars--large-3 rating-very-large')
      if res:
          print("3 star", 'whatever you want print')
      

      出来:

      3 star whatever you want print
      

      【讨论】:

      • 它工作正常,但每次都在打印“3 星,无论您想打印什么”。如何检查 class="i-stars i-stars--large-3 rating-very-large" 是 class="rating-info clearfix" 的内部类?
      猜你喜欢
      • 2018-11-04
      • 1970-01-01
      • 2021-07-09
      • 2016-11-05
      • 2016-08-05
      • 2021-10-15
      • 1970-01-01
      • 2015-08-06
      • 2019-04-07
      相关资源
      最近更新 更多