【问题标题】:Return UID attribute value using Selenium Python使用 Selenium Python 返回 UID 属性值
【发布时间】:2018-10-20 02:52:57
【问题描述】:

我有一个看起来像这样的网站,我想使用 firefox + selenium + python 提取 uid 字段的内容。每页只有 1 个 UID。

<div class= "parent" >
   <div class="module profile" dcp="1" uid="90">
   ...
   ...
   </div>
</div>

具体请看以下内容:

<div class= "parent" >
   <div class="module profile" dcp="1" uid="[RETURN THIS]">
   ...
   ...
   </div>
</div>

我在 selenium 中尝试了几种技术,包括使用

browser.find_elements_by_name
browser.find_elements_by_xpath
browser.find_elements_by_class_name
browser.find_elements_by_css_selector

但是它们都不能返回 UID。我要么得到一个空集,要么只得到类(即整个模块类而不是 DIV 内的属性)。

我看到一些人推荐了 get_attribute 选择器,但我没有成功地将它应用到这个用例中。

任何指导将不胜感激,谢谢。

【问题讨论】:

  • 请提供您尝试过的 selenium 脚本..
  • 整个脚本没有很多有用的信息。我相信我只需要一行选择器代码就可以得到这个。但是我尝试使用诸如browser.find_elements_by_class_name("module")[0] 之类的东西,但这会将整个
    返回到
    。还尝试了browser.find_elements_by_xpath("module.profile"),但这又返回了 div 的子级,而不是初始 div 块内的属性。谢谢

标签: python selenium xpath css-selectors getattribute


【解决方案1】:

要提取属性 uid 的值,即文本 90,您可以使用任一 Locator Strategies:

  • css_selector:

    myText = browser.find_element_by_css_selector("div.parent>div.module.profile").get_attribute("uid")
    
  • xpath:

    myText = browser.find_element_by_xpath("//div[@class='parent']/div[@class='module profile']").get_attribute("uid")
    

但是似乎属性 uid 即文本 90 是一个动态元素,因此您必须为 元素诱导 WebDriverWait可见,您可以使用以下任一解决方案:

  • css_selector:

    myText = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.CSS_SELECTOR, "div.parent>div.module.profile"))).get_attribute("uid")
    
  • xpath:

    myText = WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='parent']/div[@class='module profile']"))).get_attribute("uid")
    

注意:您必须添加以下导入:

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

【讨论】:

    猜你喜欢
    • 2019-03-02
    • 1970-01-01
    • 1970-01-01
    • 2021-03-01
    • 1970-01-01
    • 2013-11-09
    • 1970-01-01
    • 1970-01-01
    • 2012-08-25
    相关资源
    最近更新 更多