Selenium—有时只发送send_keys



我正在尝试制作一个脚本来登录Facebook,通过搜索栏导航到特定网页,然后点击顶部结果;但是,脚本并不总是在搜索栏中发送关键字,而是失败了。知道为什么会发生这种事吗?

我遇到的另一个困难是找到通往顶部搜索结果的正确路径。我尝试过许多不同的By.函数,如标记名、类和x路径,但似乎都不起作用。非常感谢您的帮助。

from ast import Return
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
driver = webdriver.Chrome("C:/Users/Carson/Desktop/chromedriver.exe")
driver.get("https://www.facebook.com/")

try:
username = WebDriverWait(driver, 7).until(
EC.presence_of_element_located((By.ID,'email')))

username.send_keys("username")
password = driver.find_element(By.ID, 'pass')
password.send_keys("password")
try:
driver.find_element(By.TAG_NAME, "button").click()
driver.find_element(By.XPATH, '/html/body/div[1]/div[1]/div[1]/div/div[2]/div[2]/div/div/div/div/div/label/input').click()
#clicks the search key and searches by send_keys 
search = driver.find_element(By.XPATH,'/html/body/div[1]/div[1]/div[1]/div/div[2]/div[2]/div/div/div/div/div/label/input')
search.click()
search.send_keys('The Village At Gracy Farms')
search.send_keys(Keys.RETURN)
print("nicee")

except:
print("failedddd")
driver.quit(77)
except:
print("failed")
driver.quit(22)    

Facebook主页上的搜索框元素是一个动态元素,因此理想情况下,向需要诱导WebDriver的元素发送字符序列。等待元素_to_be_clickle((,您可以使用以下定位器策略之一

  • 使用CSS_SELECTOR

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[placeholder='Search Facebook'][aria-label='Search Facebook'][aria-label='Search Facebook']"))).send_keys("The Village At Gracy Farms")
    
  • 使用XPATH:

    WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//input[@placeholder='Search Facebook' and @aria-label='Search Facebook'][@aria-expanded='true']"))).send_keys("The Village At Gracy Farms")
    
  • 注意:您必须添加以下导入:

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

相关内容

  • 没有找到相关文章

最新更新