如何通过 Selenium Python 点击​​某个元素

DKM*_*DKM 7 selenium xpath css-selectors python-2.7 webdriverwait

我正在尝试使用 selenium 浏览器 python 获取 facebook 帐户的数据,但无法找到我可以在单击导出按钮时查找的元素。

请参阅随附的屏幕截图在此输入图像描述

我尝试过,但似乎给我的班级带来了错误。

def login_facebook(self, username, password):
    chrome_options = webdriver.ChromeOptions()
    preference = {"download.default_directory": self.section_value[24]}

    chrome_options.add_experimental_option("prefs", preference)
    self.driver = webdriver.Chrome(self.section_value[20], chrome_options=chrome_options)
    self.driver.get(self.section_value[25])

    username_field = self.driver.find_element_by_id("email")
    password_field = self.driver.find_element_by_id("pass")

    username_field.send_keys(username)
    self.driver.implicitly_wait(10)

    password_field.send_keys(password)
    self.driver.implicitly_wait(10)

    self.driver.find_element_by_id("loginbutton").click()
    self.driver.implicitly_wait(10)

    self.driver.get("https://business.facebook.com/select/?next=https%3A%2F%2Fbusiness.facebook.com%2F")
    self.driver.get("https://business.facebook.com/home/accounts?business_id=698597566882728")
    self.driver.get("https://business.facebook.com/adsmanager/reporting/view?act="
                    "717590098609803&business_id=698597566882728&selected_report_id=23843123660810666")
    # self.driver.get("https://business.facebook.com/adsmanager/manage/campaigns?act=717590098609803&business_id"
    #                 "=698597566882728&tool=MANAGE_ADS&date={}-{}_{}%2Clast_month".format(self.last_month,
    #                                                                                      self.first_day_month,
    #                                                                                      self.last_day_month))

    self.driver.find_element_by_id("export_button").click()
    self.driver.implicitly_wait(10)
    self.driver.find_element_by_class_name("_43rl").click()
    self.driver.implicitly_wait(10)
Run Code Online (Sandbox Code Playgroud)

您能告诉我如何单击“导出”按钮吗?

Deb*_*anB 3

文本为Export的元素是动态生成的元素,因此要定位该元素,您必须引发WebDriverWait以使该元素可单击,并且您可以使用任一定位器策略

  • 使用CSS_SELECTOR

    WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a.layerConfirm>div[data-hover='tooltip'][data-tooltip-display='overflow']"))).click()
    
    Run Code Online (Sandbox Code Playgroud)
  • 使用XPATH

    WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[contains(@class, 'layerConfirm')]/div[@data-hover='tooltip' and text()='Export']"))).click()
    
    Run Code Online (Sandbox Code Playgroud)
  • 注意:您必须添加以下导入:

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    
    Run Code Online (Sandbox Code Playgroud)