通过文本和span/Beautiful Soup/Python提取正确的元素

通过文本和span/Beautiful Soup/Python提取正确的元素,python,beautifulsoup,Python,Beautifulsoup,我正在尝试获取以下数据: 烹饪:4.5 服务:4.0 质量:4.5 但是我在搜集正确的数据时遇到了问题。我尝试了以下两种代码: for bewertungen in soup.find_all('div', {'class' : 'histogramCommon bubbleHistogram wrap'}): if bewertungen.find(text='Cuisine'): cuisine = bewertungen.find(text='Cu

我正在尝试获取以下数据:

烹饪:4.5 服务:4.0
质量:4.5

但是我在搜集正确的数据时遇到了问题。我尝试了以下两种代码:

for bewertungen in soup.find_all('div', {'class' : 'histogramCommon bubbleHistogram wrap'}):

        if bewertungen.find(text='Cuisine'):
            cuisine = bewertungen.find(text='Cuisine')
            cuisine = cuisine.next_element
            print("test " + str(cuisine))

        if bewertungen.find_all(text='Service'):
            for s_bewertung in bewertungen.find_all('span', {'class':'ui_bubble_rating'}):
            s_speicher = s_bewertung['alt']
首先,如果我没有得到结果。在第二种情况下,如果我得到了正确的元素,但我得到了所有3个结果,但我无法定义哪些结果属于哪个文本(烹饪、服务、质量)

有人能给我一个如何获得正确数据的建议吗? 我把html代码放在底部

<div class="histogramCommon bubbleHistogram wrap">
   <div class="colTitle">\nGesamtwertung\n</div>
   <ul class="barChart">
      <li>
         <div class="ratingRow wrap">
            <div class="label part ">
               <span class="text">Cuisine</span>
            </div>
            <div class="wrap row part ">
               <span alt="4.5 of five" class="ui_bubble_rating bubble_45"></span>
        </div>
     </div>
     <div class="ratingRow wrap">
        <div class="label part ">
           <span class="text">Service</span>
        </div>
        <div class="wrap row part ">
           <span alt="4.0 of five" class="ui_bubble_rating bubble_40"></span>
            </div>
         </div>
      </li>
      <li>
         <div class="ratingRow wrap">
            <div class="label part ">
               <span class="text">Quality</span>
            </div>
            <div class="wrap row part "><span alt="4.5 of five" class="ui_bubble_rating bubble_45"></span></div>
         </div>
      </li>
   </ul>
</div>

\nGesamtwertung\n
  • 美食 服务
  • 品质

试试这个。根据上面粘贴的代码段,以下代码应该可以工作:

from bs4 import BeautifulSoup

soup = BeautifulSoup(content,"lxml")
for item in soup.select(".ratingRow"):
    category = item.select_one(".text").text
    rating = item.select_one(".row span")['alt'].split(" ")[0]
    print("{} : {}".format(category,rating))
另一种方法是:

for item in soup.select(".ratingRow"):
    category = item.select_one(".text").text
    rating = item.select_one(".text").find_parent().find_next_sibling().select_one("span")['alt'].split(" ")[0]
    print("{} : {}".format(category,rating))
输出:

Cuisine : 4.5
Service : 4.0
Quality : 4.5

你试过密码了吗?你的反馈是什么?