【问题标题】:Check if a specific class and value exist in HTML using beautifulsoup Python使用 beautifulsoup Python 检查 HTML 中是否存在特定的类和值
【发布时间】:2018-11-04 22:14:32
【问题描述】:

我正在为 scrape 网站“yelp.fr”编写脚本,但要废弃该类自动生成的星数: class="i-stars i-stars--regular-4 rating-large" ==> 4 次开始 class="i-stars i-stars--regular-3-half rating-large" ==> 3.5

我的问题是如何做到这一点?以及如何判断类是否存在于 html 页面上

CITIES = "la rochelle(17000)"
places = "Bars"
driver = webdriver.Chrome()
driver.get("https://www.yelp.fr/search?find_desc="+places+"&find_loc="+CITIES+"")
page = driver.page_source
soup = BeautifulSoup(page,"lxml")
etoiles=soup.find_all("div",{"class":"biz-rating biz-rating-large clearfix"})
                    
etoiles.get_attribute("title")
if etoiles:
    print "ok"
else:
    print "not "

有时类 biz-rating biz-rating-large clearfix 不存在如下

【问题讨论】:

    标签: python selenium-webdriver beautifulsoup selenium-chromedriver


    【解决方案1】:

    DIVtitle 包含星数/评分。你可以得到它像

    ratings = soup.select(".i-stars")
    for rating in ratings:
        print rating.attrs['title']
    

    【讨论】:

    • 我测试了你的提议,但该字段没有像“le Set bar”这样的星号影响默认值 5.0 星
    【解决方案2】:

    我用这个解决了问题:

    yelp_url  = "https://www.yelp.com/search?find_desc=%s&find_loc=%s&start=%s"%(place,city,str(id))
    
            headers1 = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.90 Safari/537.36'}
            response1 = requests.get(yelp_url).text
            parser = html.fromstring(response1)
            print "Parsing the page"
            listing1 = parser.xpath("//li[@class='regular-search-result']")
    for results in listing1:
    if raw_ratings:
                            ratings = re.findall("\d+[.,]?\d+",cleaned_ratings)[0]
                        else:
                            ratings = 0
                        price_range = len(''.join(raw_price_range)) if raw_price_range else 0
                        address  = ' '.join(' '.join(raw_address).split())
                        address=unidecode(address)
                        reservation_available = True if is_reservation_available else False
                        accept_pickup = True if is_accept_pickup else False
    

    【讨论】:

      【解决方案3】:
      raw_review_count = results.xpath(".//span[contains(@class,'review-count')]//text()")
                          raw_price_range = results.xpath(".//span[contains(@class,'price-range')]//text()")
      if raw_ratings:
                              ratings = re.findall("\d+[.,]?\d+",cleaned_ratings)[0]
                          else:
                              ratings = 0
                          price_range = len(''.join(raw_price_range)) if raw_price_range else 0
      

      【讨论】:

        猜你喜欢
        • 2017-04-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-07-09
        • 2016-11-05
        • 2016-08-05
        相关资源
        最近更新 更多