Python,Selenium Webdriver:如何找到此属性的值?

问题描述 投票:0回答:1

我正在研究一个python脚本,以使用硒Chrome浏览器网络驱动程序从网站获取一些数据。直到现在为止,找到所需的元素对我来说都很好。现在,我正在尝试获取广告ID(“ data-ad-link”的值。

<div class="header w-brk" style="overflow-wrap: break-word;">
        <a href="/iad/immobilien/d/eigentumswohnung/wien/wien-1010-innere-stadt/am-werdertor-etages-de-luxe-344939582/" class="" data-ad-link="344939582">
            <span itemprop="name">
                AM WERDERTOR - ÉTAGES DE LUXE
            </span>
        </a>
    </div>

从这个HTML片段中,我需要data-ad-link的值。我尝试使用

解决此问题
elem = driver.find_elements_by_xpath("//*[@class='']")
for i in range(count):
    #uniqueid = elem[i].get_attribute('data-ad-link')
    #uniqueid = driver.execute_script('var items = {}; for (index = 0; index < arguments[0].attributes.length; ++index) { items[arguments[0].attributes[index].name] = arguments[0].attributes[index].value }; return items;', elem[i])
    print(uniqueid)

在调试器中,我看到创建列表的效果很好-但是获取值却不行。所以我已经尝试过element.get_attribute,它返回了None(也用于href!)。我尝试了在这里找到的driver.execute_scriptSelenium webdriver: How do I find ALL of an element's attributes?只是给了我class,href和rel。

有人知道我将如何获得这一价值?这对我有很大帮助!

我在Python上使用Selenium(v 3.141.0)

python selenium selenium-webdriver xpath webdriverwait
1个回答
0
投票

要提取属性data-ad-link的值,即344939582,您必须为所需的visibility_of_element_located()引入WebDriverWait,并且可以使用以下Locator Strategy

  • 使用XPATH

    print(WebDriverWait(browser, 20).until(EC.visibility_of_element_located((By.XPATH, "//div[@class='header w-brk']/a[starts-with(@href, '/iad/immobilien/d/eigentumswohnung/wien/wien-')]/span[@itemprop='name' and normalize-space()='AM WERDERTOR - ÉTAGES DE LUXE']/.."))).get_attribute("data-ad-link"))
    
© www.soinside.com 2019 - 2024. All rights reserved.