如何在div中单击?

2024-10-01 02:28:32 发布

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

我正在尝试在不同的div类TopBox上执行单击。我尝试了以下代码,但没有执行单击: Snapshot

driver.find_element_by_css_selector('#home > div > div.row.topBoxs > div.col-xs-12.col-lg-10 > div > div:nth-child(1) > div').click()

而且:

driver.find_element_by_xpath('//*[@id="home"]/div/div[2]/div[1]/div/div[1]').click()

下面是示例框“mes posts”和其他框的代码快照。 Mes Posts HTML codeHTML code :


Tags: 代码divhomebydrivercolelementfind
3条回答

这是你必须做的

# get number of the toolboxes first
toolBoxes = len(driver.find_element_by_css_selector("div.boxs div[class^='topBox ']"))

# now you can click on each of them
for boxNumber in range(toolBoxes):
    # you can use either xpath/css to get the nth box and click()
    driver.find_element_by_xpath("(//div[@class='boxs']/div[starts-with(@class,'topBox ')])[" + str(boxNumber+1) + "]").click()
    # waiting here so that you can see the element is clicked (optional)
    time.sleep(2)
  1. 首先,检查您是否能够找到元素。如果不是,则以下行应为抛出错误:

    WebElement theButton = driver.find_element_by_xpath('//div[@class='boxs']/div[1]/div');
    

或者,也请尝试使用此xpath

    '//div[@class='boxs']/div[1]/div/div/p/span'
  1. 等待该元素,直到其可单击为止

    wait = WebDriverWait(driver, 15)
    wait.until(EC.element_to_be_clickable((By.XPATH, my_xpath)))
    
  2. 然后尝试使用单击元素。单击()

请让我知道您的观察结果,这将有助于排除故障

尝试使用xpath而不是css_selector

driver.find_element_by_xpath('xpath_of_your_Div').click()

相关问题 更多 >