通过Selenium单击Twitter的“收藏夹”按钮无效

时间:2018-09-16 01:52:22

标签: python selenium twitter web-scraping

我当时使用Python脚本登录我的Twitter帐户,然后在我的时间轴上单击每个推文的“收藏夹”按钮。即使可以定位按钮元素并且控制台输出显示每个按钮都被单击,但似乎完全没有效果-当我登录自己的帐户进行检查时,发现没有“喜欢”任何推文。有人知道偏爱机制的工作原理吗?

from selenium import webdriver
from getpass import getpass
from pyvirtualdisplay import Display
import sys
import codecs
from selenium.webdriver.support import expected_conditions as EC
import time
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.action_chains import ActionChains

sys.stdout = codecs.getwriter('utf8')(sys.stdout)
sys.stderr = codecs.getwriter('utf8')(sys.stderr)

def login_twitter(username, password, driver):

    username_field = driver.find_element_by_class_name("js-username-field")
    password_field = driver.find_element_by_class_name("js-password-field")

    username_field.send_keys(username)
    driver.implicitly_wait(1)

    password_field.send_keys(password)
    driver.implicitly_wait(1)

    driver.find_element_by_class_name("EdgeButtom--medium").click()

    driver.implicitly_wait(10)
    print("Login OK")

    elements = driver.find_elements_by_class_name("ProfileTweet-action--favorite")

    print("Found " + str(len(elements)) + " elements")

    for e in elements:
        try:
            print("Waiting for element to be visible")
            WebDriverWait(driver, 10).until(EC.visibility_of(e))
            print("clicking " + str(e))
            ActionChains(driver).move_to_element(e).click().perform()
            print("clicked " + str(e.text))
            time.sleep(1)
        except Exception as e:
            print(str(e))

if __name__ == "__main__":
    username = input("user name : ")
    password = getpass("password  : ")

    display = Display(visible=0, size=(1024, 2048))
    display.start()

    driver = webdriver.Firefox()
    driver.get("https://twitter.com/login")

    try:
        login_twitter(username, password, driver)
    except Exception as e:
        print(str(e))

    driver.quit()
    display.stop()

0 个答案:

没有答案