查找并单击具有更改的CSS选择器的元素(python) [英] find and click element which has a changing CSS selector (python)

查看:121
本文介绍了查找并单击具有更改的CSS选择器的元素(python)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本,该脚本需要单击页面的某个元素,但是CSS选择器每天都会随着该元素更改其位置而变化.

I am writing a script which needs to click on an element of a page, however, the CSS selector changes everyday as the element changes it's location.

今天叫做:

PPTAmFCTable > tbody:nth-child(1) > tr:nth-child(11) > td:nth-child(3) > a:nth-child(1)

昨天是:

PPTAmFCTable > tbody:nth-child(1) > tr:nth-child(10) > td:nth-child(3) > a:nth-child(1)

明天可能是tr:nth-child(13)左右.

我使用以下代码:

def click_element_bycss(browser,css,timeout):
    element_present = EC.presence_of_element_located((By.CSS_SELECTOR,css)) 
    WebDriverWait(browser, timeout).until(element_present)
    browser.find_element_by_css_selector(css).click()

然后:

click_element_bycss(browser,"#PPTAmFCTable > tbody:nth-child(1) > tr:nth-child(11) > td:nth-child(3) > a:nth-child(1)",4)

在不知道第二个tr:nth-​​child()中的数字的情况下,如何以单击右侧元素的方式编写代码?

How can I write the code in a way that I click on the right element, w/o knowing the number in the second tr:nth-child() ?

元素HTML:

<a href="/FC1/ItemList;jsessionid=E6B3D538CD809FDDC3DE69EA160C956D?WorkPool=PickingNotYetPicked&amp;ExSDRange.RangeEndMillis=1556850660000&amp;ProcessPath=PPTAmFC&amp;ExSDRange.RangeStartMillis=1556850599999&amp;shipmentType=TRANSSHIPMENTS">261</a>

想到了一个循环 对于范围(1,20)中的i:tr:nth-​​child(i) 但会希望有更聪明的东西.

Thought of a loop which just runs through for i in range(1,20): tr:nth-child(i) but would expect there's something smarter.

推荐答案

要查找并单击该元素,因为该元素是动态元素,您需要为element_to_be_clickable()引入 WebDriverWait ,并且您可以使用以下任一定位器策略:

To find and click on the element as the element is a dynamic element you need to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

  • 使用CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "#PPTAmFCTable>tbody a[href^='/FC1/ItemList'][href$='TRANSSHIPMENTS']"))).click()

  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//*[@id='PPTAmFCTable' and starts-with(@href,'/FC1/ItemList')][contains(@href, 'TRANSSHIPMENTS')]")))
    

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

  • Note : You have to add the following imports :

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

  • 这篇关于查找并单击具有更改的CSS选择器的元素(python)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆