无法从span标签提取文本

时间:2019-07-10 10:04:19

标签: python selenium selenium-webdriver

我正在将Selenium与Python结合使用来进行某些Web抓取。网站HTML具有以下span标签:

<span class="item-stats-value ng-binding ng-scope" ng-if="value > 0 &amp;&amp; isPercentage">90<!-- ngIf: isPercentage --><span ng-if="isPercentage" class="ng-scope">%</span><!-- end ngIf: isPercentage --> </span>

我想提取此处的文本90,但通常的find_element_by_class_name("item-stats-value").text返回一个空字符串。有什么方法可以获取此文本值?

编辑:代码更正

编辑:代码澄清:

# Gets list of all the stats
stats = self.driver.find_elements_by_class_name("item-stats-stat")

# Gets text from each stat - stat is an <li> and the text is in a <span> inside it
for stat in stats:
    value = stat.find_element_by_class_name("item-stats-value").text

编辑:更多HTML

More HTML for clarification

2 个答案:

答案 0 :(得分:0)

Xpath

如果像这样简单的事情

std::array<std::array<std::array<std::array<double, 2>, 3>, 6>, 100> my_array;
constexpr auto sz = arr_sz<decltype(my_array)>::size;
static_assert(sz == sizeof(double) * 2 * 3 * 6 * 100, ""); 

不起作用,您可以尝试另一个解决方案,即xpath。该查询看起来像stats = self.driver.find_elements_by_class_name("item-stats-value") for stat in stats: value = stat.text

并按照以下步骤实施

//*[contains(@class,’item-stats-stat’)]//*[contains(@class,’item-stats-value’)]

选中此项以获取选择器https://johnresig.com/blog/xpath-css-selectors/

的参考

对于嵌套选择Select deeply nested element

答案 1 :(得分:0)

尝试以下选项。希望这将返回预期的输出。

stats =self.driver.find_elements_by_css_selector(".item-stats-stat")

# Gets text from each stat - stat is an <li> and the text is in a <span> inside it
for stat in stats:
    value = stat.find_element_by_xpath("./span[@class='item-stats-value ng-binding ng-scope']").text