硒xpath元素属性

2024-10-03 06:31:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从“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中工作,并突出显示了我想要的内容:

^{pr2}$

但是每次运行代码都会超时?我的代码如下:

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()

提前谢谢


Tags: importselfdivurldatadrivercarclass
3条回答

我将依赖于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应用于代码:

^{pr2}$

另外,还有一个CSS选择器:

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

您可以首先通过XPath获取元素,然后使用WebElement的方法get_attribute检索所需的信息。在

示例:

element = driver.find_elements_by_xpath(urlXpath)
nice_url = element.get_attribute("data-nice_url")
urlXpath = //div[@class="car-thumb-item clickable vehicle"] 
nice_url = driver.find_element_by_xpath(urlXpath).get_attribute("data-nice_url")

相关问题 更多 >