无法让Selenium找到元素

时间:2017-02-14 19:31:41

标签: c# selenium elements

我想在yelp.com上找到一个元素。我尝试过使用foreach ($array as $value) { echo $value->android; } xPath,但似乎无法检索每个商家的星级评分。

这是星级HTML:

ClassNames

以下是我检索评分的代码:

<div class="i-stars i-stars--regular-4-half rating-large" title="4.5 star rating">
    <img class="offscreen" height="303" src="https://s3-media1.fl.yelpcdn.com/assets/srv0/yelp_design_web/41341496d9db/assets/img/stars/stars.png" width="84" alt="4.5 star rating">
</div>

我希望它返回var starRating = driverGC.FindElement(By.LinkText("title")); MessageBox.Show(starRating.Text); ,以便将其保存到另一个文件中。我正在使用C#和Visual Studio。

2 个答案:

答案 0 :(得分:0)

如果您只有一个结果,我认为您可以这样做。或者,如果您需要查找特定评级,请根据需要对其进行自定义:

// The rating element
var starRating = driverGC.FindElement(By.ClassName("i-stars"));
// The title attribute on the rating element is something like '4.5 star rating'
// which I think is what you're trying to find.
MessageBox.Show(starRating.GetAttribute("title").Split(' ').First());   

或者,如果你想循环遍历所有元素:

// The rating element
IList<IWebElement> starRatings = driverGC.FindElements(By.ClassName("i-stars"));
// The title attribute on the rating element is something like '4.5 star rating'
// which I think is what you're trying to find.
foreach (IWebElement elem in starRatings)
{
    MessageBox.Show(elem.GetAttribute("title")Split(' ').First());  
} 

Split(' ').First()应返回第一个单词,即4.5。注意:您需要using System.Linq;语句才能使用First(),或者最终使用ToList()

答案 1 :(得分:0)

您可以找到并过滤此类商家(使用Java):

List<WebElement> starRatings = driver.findElements(By.xpath("//div[contains(@title, 'star rating')]"));
List<WebElement> businesses = driver.findElements(By.xpath("//div[contains(@title, 'star rating')]/preceding::a[1]/span"));
for(int i = 0; i < starRatings.size(); i++)
{
       String rating = starRatings.get(i).getAttribute("title");
       rating = rating.split(" ")[0];
       DecimalFormat df = new DecimalFormat("#.#");
       Double d = Double.valueOf(rating);
       rating = df.format(d);
       d = Double.valueOf(rating);
       if(d <= 3)
       {
            String Businessname = businesses.get(i).getText();
            //Write variable Businessname & rating into file 
       }
}