Python - Selenium - 如何查找特定项目的 XPATH

问题描述 投票:0回答:1

我有一个能够遍历多个页面的网页...现在我需要从具有项目列表的网页中选择一个特定的项目/按钮。不确定如何根据检查视图使用 XPATH 或 CLASS OR 等找到该项目。

def select_requested_colony(colony):
    #//*[@id="zd"]/div[2]/div[2]/div[1]/div[1]/div/p[2]

    try:
        print("================== select_requested_colony ==============")
        print(f"Find Colony: {colony}")
       
        time.sleep(2)

        xpath = f"//*[@id=\"zd\"] //*[contains(text(), '{colony}')]"
        print(f"XPATH: {xpath}")
        
        # Wait for the element to be clickable
        colony_button = WebDriverWait(driver, 10).until(
            EC.element_to_be_clickable((By.XPATH, xpath))
        )
        print("FOUND Colony....")
        print(f"Button Text: {colony_button.text}")
        colony_button.Click()
    
        time.sleep(20)
        
    except Exception as e:
        print(f"select_requested_colony -- An error occurred: {str(e)}")

输出是:

================== select_requested_colony ==============
Find Colony: Big Rose, MT
XPATH: //*[@id="zd"] //*[contains(text(), 'Big Rose, MT')]
FOUND Colony....
Button Text: Big Rose, MT
select_requested_colony -- An error occurred: 'WebElement' object has no attribute 'Click'

Inspect of web page that has list of colonies... HOW TO FIND SPECIFIC COLONY AND SELECT IT AS A BUTTON

尝试了多种方法来查找按钮。

python selenium-webdriver web-scraping
1个回答
0
投票

为了查找元素的 xpath,您可以简单地在浏览器中:

  1. 右键单击该元素并选择“检查”。这将打开开发工具窗口。
  2. 现在右键单击突出显示的元素(如果突出显示了错误的元素,则右键单击另一个元素)
  3. 选择复制>复制xpath

但是,就您收到的错误而言,有不同的原因。您已写道:

colony_button.Click()

而在 Selenium 中应该是:

colony_button.click()

(小写“c”)

© www.soinside.com 2019 - 2024. All rights reserved.