如何使用Selenium Python提取属性图片列表的值

时间:2019-07-15 21:08:06

标签: python-3.x selenium xpath css-selectors webdriverwait

下面有这个代码

<div class="gallery-list">
<figure class="figure" ng-class="profileGallery.css" profile-item-remove="9>
<a href="https://#" data-login="" gallery-modal="9" rel="nofollow">
<picture sl-video-preview="https://movie.mp4" sl-safe="" class="ng-isolate- 
scope sl-safe">
</a>
</figure>
<figure class="figure hd" ng-class="profileGallery.css" profile-item- 
 remove="9>
<a href="https://#" data-login="" gallery-modal="9" rel="nofollow">
<picture sl-video-preview="https://movie.mp4" sl-safe="" class="ng-isolate- 
 scope sl-safe">
</a>
</figure>
<figure class="figure" ng-class="profileGallery.css" profile-item-remove="9>
<a href="https://#" data-login="" gallery-modal="9" rel="nofollow">
<picture sl-video-preview="https://movie.mp4" sl-safe="" class="ng-isolate- 
 scope sl-safe">
</a>
  </figure>
<div>

Xpath

print(WebDriverWait(driver, 
20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='gallery- 
list']/figure[@class='figure hd']/a/picture[@class='ng-isolate-scope sl- 
safe']"))).get_attribute("sl-video-preview"))

使用此xpath代码,可以获得一条属性图记录,但这是动态的,有时我有一,二,三,十二或五十。 如何通过xpath sl-video-preview获取具有列表动态大小的所有出现的属性值。

3 个答案:

答案 0 :(得分:0)

此答案是Java语言。

Range1d

答案 1 :(得分:0)

您需要修改函数以使用find_elements_by_xpath,该函数返回List中的WebElements,因为当前代码仅返回与提供的定位符匹配的单个(第一个)WebElement。

建议的代码更改:

pictures = WebDriverWait(driver, 10).until(EC.presence_of_all_elements_located((By.XPATH, "//picture")))
for picture in pictures:
    print(picture.get_attribute('sl-video-preview'))

展望未来,您可以考虑将代码重构为使用Page Object Model Design Pattern,这样您就可以从lazy initialization方法中受益,而不必一直定义Waits

答案 2 :(得分:0)

您似乎很接近。对于<figure>节点,您已经考虑了类figurehd,但它们都没有,因此您需要遍历它们。另外,您需要使用visibility_of_element_located()来代替visibility_of_all_elements_located(),并且可以使用以下任一解决方案:

  • 使用CSS_SELECTOR

    print([my_elem.get_attribute("sl-video-preview") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "div.gallery-list figure.figure picture.ng-isolate-scope.sl-safe")))])
    
  • 使用XPATH

    print([my_elem.get_attribute("sl-video-preview") for my_elem in WebDriverWait(driver, 5).until(EC.visibility_of_all_elements_located((By.XPATH, "//div[@class='gallery-list']//figure[contains(@class, 'figure')]//picture[@class='ng-isolate-scope sl-safe']")))])
    
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC