Python和Selenium:无法找到并单击Facebook的“喜欢和分享”按钮

时间:2019-03-20 09:10:05

标签: python selenium

我试图在具有xpath的Facebook页面上找到“赞”和“共享”按钮,但是在加载Facebook页面后,Python脚本执行完成,并且没有单击like按钮。

我从Facebook页面上获得了类似的按钮xpath。

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time

def connect():
    driver.set_page_load_timeout("10")
    driver.get("https://www.facebook.com/mytheoryofevolution/")
    time.sleep(4)

chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

driver = webdriver.Chrome(executable_path=r"C:\Users\javed\PycharmProjects\click-website\drivers\chromedriver.exe",chrome_options=chrome_options)


connect()

like_buttons = driver.find_elements_by_xpath('//a[contains(@class,"likeButton")]')

for like in like_buttons:
    print(like)
    break

1 个答案:

答案 0 :(得分:0)

您不需要

break

因为它将在开始for循环时获得第一项,然后循环中断

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
import time


chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:9222")

driver = webdriver.Chrome(executable_path=r"C:\Users\javed\PycharmProjects\click-website\drivers\chromedriver.exe",chrome_options=chrome_options)

def connect():
    driver.set_page_load_timeout("10")
    driver.get("https://www.facebook.com/mytheoryofevolution/")
    time.sleep(4)
    like_buttons = driver.find_elements_by_xpath('//a[contains(@class,"likeButton")]')

    for like in like_buttons:
        print(like)

connect()