Python碎片星星级

时间:2018-06-21 13:51:11

标签: python-3.x splinter

给出“最近评论”部分here下的星级,

我正在尝试构建页面上显示的每个评论的星级评分列表。 问题在于每个星级评定对象都没有值。 例如,我可以像这样通过xpath获得单个星体对象:

from splinter import Browser

url = 'https://www.greatschools.org/texas/harker-heights/3978-Harker-Heights-Elementary-School/'
browser.visit(url)

astar=browser.find_by_xpath('/html/body/div[5]/div[4]/div[2]/div[11]/div/div/div[2]/div/div/div[2]/div/div[2]/div[3]/div/div[2]/div[1]/div[2]/span/span[1]')

问题是我似乎无法访问astar对象的值(是否填写)。

这是HTML:

<div class="answer">
 <span class="five-stars">
  <span class="icon-star filled-star"></span>
  <span class="icon-star filled-star"></span>
  <span class="icon-star filled-star"></span>
  <span class="icon-star filled-star"></span>
  <span class="icon-star filled-star"></span>
 </span>
</div>

更新: 有些评论根本没有星级,因此我需要确定特定评论是否具有星级,如果是,则是什么星级。 This似乎有助于至少获得所有星星的列表。我用它来做到这一点:

stars = browser.find_by_css('span[class="icon-star filled-star"]')

因此,如果我可以得到一个列表,显示评论是否具有星级(例如评分= [1,0,1,1 ...])和所有星级(即['Filled ','Filled','Empty'...]),我想我可以拼凑顺序。

1 个答案:

答案 0 :(得分:0)

一种解决方案: 像这样访问每个对象的html属性:

#Get total number of comments
allcoms = len(browser.find_by_text('Overall experience'))

#Loop through all comments and gather into list
comments = []
#If pop-up box occurs, use div[4] instead of second div[5]
if browser.is_element_present_by_xpath('/html/body/div[5]/div[4]/div[2]/div[11]/div/div/div[2]/div/div/div[2]/div/div[2]/div[1]/div/div[2]'):
    use='4'
else:
    use='5'

for n in range(allcoms): #sometimes the second div[5] was div[4]
    comments.append(browser.find_by_xpath('/html/body/div[5]/div['+use+']/div[2]/div[11]/div/div/div[2]/div/div/div[2]/div/div[2]/div['+str(n+1)+']/div/div[2]').value)

#Get all corresponding star ratings
#https://stackoverflow.com/questions/46468030/how-select-class-div-tag-in-splinter
ratingcode = []
ratings = browser.find_by_css('span[class="five-stars"]')
for a in range(len(comments)+2): #Add 2 to skip over first 2 ratings
    if a<2: #skip first 2 and last 3 because these are other ratings - by just using range(len(comments)) above to get correct # before stopping
        pass
    else:
        ratingcode.append(ratings[a].html)