【问题标题】:Selenium xpath element attributeSelenium xpath 元素属性
【发布时间】:2015-10-20 10:13:39
【问题描述】:

我正在尝试从“data-nice-url”元素中获取属性,我的 html 如下所示:

<div class="car-thumb-item clickable vehicle " data-include_settings="true" data-nice_url="/privatleasing/Citro%c3%abn-Berlingo/eHDi-90-Seduction-E6G" data-id="34285" style="display: block;">
<div class="car-thumb-brand">Citroën</div>
<div class="car-thumb-model">Berlingo </div>
<div class="car-thumb-variant">eHDi 90 Seduction E6G</div>
<div class="car-thumb-image" style="background-image: url('https://online.leasingcar.dk/Views/Public/GetPDFDocument.aspx?imageId=18442')"/>
<div class="car-thumb-details clearfix">
<div class="car-thumb-specs">1. ydelse 24.838 Kr. | 36 mdr. | 15.000 Km     | Inkl. service | Inkl. moms</div>
</div>

我想要的结果是:"/privatleasing/Citro%c3%abn-Berlingo/eHDi-90-Seduction-E6G"

以下 xpath 似乎在 Firepath 中有效,并突出显示了我想要的内容:

//div[@class='car-thumb-item clickable vehicle   ']/@data-nice_url

但是当我运行代码时,它每次都会超时?我的代码如下所示:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
import unittest


class DataTest(unittest.TestCase):
def setUp(self):
    self.driver = webdriver.Firefox()
    self.driver.get("http://www.leasingcar.dk/privatleasing")

def testData(self):
    driver = self.driver
    urlXpath = "//div[@class='car-thumb-item clickable vehicle   ']/@ data-nice_url"

    carLinks = WebDriverWait(driver, 30).until(lambda driver:  driver.find_elements_by_xpath(urlXpath))

    for car in carLinks:
        print car

def tearDown(self):
    self.driver.quit()


if __name__ == '__main__':
unittest.main()

提前致谢

【问题讨论】:

    标签: python html selenium xpath selenium-webdriver


    【解决方案1】:

    我会依赖 data-nice_url 属性和 vehicle 类的存在:

    vehicle = driver.find_element_by_xpath('//div[@data-nice_url and contains(@class, "vehicle")]')
    print(vehicle.get_attribute("data-nice_url")
    

    WebDriverWait 应用于您的代码:

    wait = WebDriverWait(driver, 30)
    car_links = wait.until(lambda driver: driver.find_elements_by_xpath('//div[@data-nice_url and contains(@class, "vehicle")]'))
    
    for car in carLinks:
        print car
    

    另外,一个 CSS 选择器:

    vehicle = driver.find_element_by_css_selector('div.vehicle[data-nice_url]')
    print(vehicle.get_attribute("data-nice_url")
    

    【讨论】:

      【解决方案2】:

      你可以先通过XPath获取一个元素,然后使用WebElement的方法get_attribute获取你需要的信息。

      例子:

      element = driver.find_elements_by_xpath(urlXpath)
      nice_url = element.get_attribute("data-nice_url")
      

      【讨论】:

        【解决方案3】:
        urlXpath = //div[@class="car-thumb-item clickable vehicle"] 
        nice_url = driver.find_element_by_xpath(urlXpath).get_attribute("data-nice_url")
        

        【讨论】:

          猜你喜欢
          • 2017-10-15
          • 2021-03-14
          • 1970-01-01
          • 1970-01-01
          • 2015-09-14
          • 2012-12-24
          • 1970-01-01
          • 1970-01-01
          • 2021-02-12
          相关资源
          最近更新 更多