我想使用Selenium webdriver迭代Python中的以下元素。
<ul class="skills-section">
<li class="endorse-item has-endorsements " data-endorsed-item-name="Ear Surgery">
<li class="endorse-item has-endorsements " data-endorsed-item-name="Healthcare">
<li class="endorse-item has-endorsements " data-endorsed-item-name="Hospitals">
<li class="endorse-item has-endorsements " data-endorsed-item-name="Surgery">
<li class="endorse-item has-endorsements " data-endorsed-item-name="Medical Education">
<li class="endorse-item has-endorsements " data-endorsed-item-name="Pediatrics">
<li class="endorse-item has-endorsements " data-endorsed-item-name="Treatment">
<li class="endorse-item has-endorsements " data-endorsed-item-name="Public Health">
<li class="endorse-item has-endorsements " data-endorsed-item-name="Patient Safety">
<li class="endorse-item has-endorsements " data-endorsed-item-name="Emergency Medicine">
</ul>
我尝试了什么?
skillsSection = a.find_element_by_xpath("//ul[contains(@class, 'skills-section')]")
skillsList = skillsSection.find_elements_by_tag_name("li")
for skill in skillsList:
print skill.find_element_by_xpath("//span[contains(@class,endorse-item-name')]/a").text
但问题是,它总是打印第一个元素值。元素没有递增。
答案 0 :(得分:1)
您要做的是找到带有'ul'
的标记class='skills-section'
,然后对子项进行迭代。
skillsSection = a.find_element_by_xpath("//ul[contains(@class, 'skills-section')]")
for child in skillsSection.find_elements_by_xpath(".//*"):
...
有关详细信息,请参阅此答案:Selenium Python get all children elements
答案 1 :(得分:0)
我最近一直处理类似的问题,我只能打印列表中的第一项。我发现了一个需要多行的解决方案,并避免使用xpath。对于您的代码,您可能需要替换:
print skill.find_element_by_xpath("//span[contains(@class,'endorse-item-name')]/a").text
有类似的东西:
a1 = skill.find_element_by_class_name('endorse-item-name')
a2 = a1.find_element_by_tag_name('a')
print a2.text
不像xpath那样优雅,但它(应该)有用。