如何使用Python获取Selenium中的第10个< li>元素< ul>?

6xfqseft  于 2023-01-02  发布在  Python
关注(0)|答案(2)|浏览(325)

I want to get the 10th value ie. value ofPrice/Bookof the 10th in an .

我试过以下方法,但没有效果。每次我得到第一个元素时,都不是第10个元素。

block = driver.find_element(by=By.XPATH, value="//ul[contains(@class, 'small-block-grid-3 large-block-grid-4 sal-component-band-grid')]/li[10]")
value = block.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-value')]").text
block = driver.find_element(by=By.XPATH, value="//ul[contains(@class, 'small-block-grid-3 large-block-grid-4 sal-component-band-grid')]/li[position()=10]")
value = block.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-value')]").text
block = driver.find_element(by=By.XPATH, value="//ul[contains(@class, 'small-block-grid-3 large-block-grid-4 sal-component-band-grid')]").find_element(by=By.XPATH, value="//li[10][contains(@class, 'snap-panel')]")
value = block.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-value')]").text
block = driver.find_element(by=By.XPATH, value="//ul[contains(@class, 'small-block-grid-3 large-block-grid-4 sal-component-band-grid')]").find_element(by=By.XPATH, value="//li[position()=10][contains(@class, 'snap-panel')]")
value = block.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-value')]").text
block = driver.find_element(by=By.XPATH, value="//ul[contains(@class, 'small-block-grid-3 large-block-grid-4 sal-component-band-grid')]").find_elements(by=By.XPATH, value="//li[contains(@class, 'snap-panel')]")
for item in block:
    name = item.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-name')]").text
    if 'Price/Book' in name:
        value = item.find_element(by=By.XPATH, value="//div[contains(@class, 'dp-value')]").text

我怎样才能得到第10个元素?

clj7thdc

clj7thdc1#

您可以使用以下XPATH获取第10个<li>dp-value

value = (.//ul[@class='small-block-grid-3 large-block-grid-4 sal-component-band-grid']/li)[10]//div[@class='dp-value'].text
w6lpcovy

w6lpcovy2#

要获得第n个元素,有一个CSS选择器!
使用nth-of-tye CSS选择器:

li:nth-of-type(10)

例如,在您的情况下:

driver.find_element_by_css_selector("li:nth-of-type(10)").click()

这将查找第10个<li>标记。
您还可以将其与其他CSS选择器组合使用以缩小搜索范围,例如,您的CSS选择器可以是:

li:nth-of-type(10) .CLASS-NAME

.用于选择CSS类。

另请参见

CSS selectors (w3schools)

相关问题