一尘不染

使用selenium登录Facebook

selenium

我知道这不是一个适当的技术问题,但是在使用selenium制作Facebook发布机器人时,我遇到了问题。到目前为止,这是我的代码

    from selenium import webdriver

browser = webdriver.Firefox(executable_path='D:\\soft\\geckodriver-v0.18.0-win64\\geckodriver.exe')
browser.get('http://www.facebook.com')
emailElem = browser.find_element_by_id('email')
passElem = browser.find_element_by_id('pass')
submitIt = browser.find_element_by_id('u_0_r')
email_id = 'xxxxxxxxxxxxxx'
password = 'xxxxxxx'
status = 'Hie all'
emailElem.send_keys(email_id)
passElem.send_keys(password)
submitIt.click()
statusBox = browser.find_element_by_xpath(
   "//*[@id='js_kk']/div[1]/div/div[1]/div[2]/div/div/div/div/div/div[2]/div/div/div/div/span/br")
statusBox.send_keys("Hie")

现在,问题是我的代码无法在Fb页面中找到状态框,我对selenium还是很陌生。任何帮助都很好,它是用python编码的。


阅读 707

收藏
2020-06-26

共1个答案

一尘不染

这是访问的示例代码块 Facebook Login Page
,通过一组有效的凭据登录,并在以及中使用键入 “ Hie”Status Boxxpath``css_selector


使用XPATH:

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

driver = webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("https://www.facebook.com/")
driver.find_element_by_xpath("//input[@id='email']").send_keys("email@domain.com")
driver.find_element_by_xpath("//input[@id='pass']").send_keys("password")
driver.find_element_by_xpath("//input[starts-with(@id, 'u_0_')][@value='Log In']").click()
print(driver.title)
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.XPATH, "//div[starts-with(@id, 'u_0_')]//textarea[@name='xhpc_message']")))
driver.find_element_by_xpath("//div[starts-with(@id, 'u_0_')]//textarea[@name='xhpc_message']").send_keys("Hie")
print("Typed Hie within Facebook Status Box")

使用CSS_SELECTOR:

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

driver = webdriver.Firefox(executable_path=r'C:\Utility\BrowserDrivers\geckodriver.exe')
driver.get("https://www.facebook.com/")
driver.find_element_by_css_selector("input#email").send_keys("email@domain.com")
driver.find_element_by_css_selector("input#pass").send_keys("password")
driver.find_element_by_css_selector("input[id^='u_0_'][value='Log In']").click()
print(driver.title)
WebDriverWait(driver, 5).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "div[id^='u_0_'] textarea[name=xhpc_message]")))
driver.find_element_by_css_selector("div[id^='u_0_'] textarea[name=xhpc_message]").send_keys("Hie")
print("Typed Hie within Facebook Status Box")
2020-06-26