找到并单击具有更改CSS选择器的元素(python)
作者:互联网
我正在编写一个需要单击页面元素的脚本,但是,当元素更改其位置时,CSS选择器会每天更改.
今天它被称为:
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()中的数字?
元素HTML:
<a href="/FC1/ItemList;jsessionid=E6B3D538CD809FDDC3DE69EA160C956D?WorkPool=PickingNotYetPicked&ExSDRange.RangeEndMillis=1556850660000&ProcessPath=PPTAmFC&ExSDRange.RangeStartMillis=1556850599999&shipmentType=TRANSSHIPMENTS">261</a>
想到一个刚刚贯穿的循环
我在范围内(1,20):tr:nth-child(i)
但是会期待有更聪明的东西.
解决方法:
要查找并单击元素,因为元素是动态元素,您需要为element_to_be_clickable()引入WebDriverWait,并且可以使用以下任一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')]")))
>注意:您必须添加以下导入:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
标签:python,css-selectors,selenium,xpath,webdriverwait 来源: https://codeday.me/bug/20191009/1876408.html