首页 > 解决方案 > Python & Selenium:无法定位和点击 Facebook 的点赞和分享按钮

问题描述

我正在尝试使用 xpath 在 facebook 页面上找到“Like”和“Share”按钮,但是在 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

标签: pythonselenium

解决方案


t你不需要

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()



推荐阅读