Seleniumを使ってTwitterアカウントをミュートする

書いた。selenium使うと色々できそう。

I used this method to get my mute list in my old account (It's to be deleted) and using the list I mute the same accounts in my new it.

Needed: python3, selenium, chromedriver, chrome

Create a mute list

Go to muted or muted_following, and keep scrolling down until you’ve loaded everyone you mute. Open your developer console. In Chrome, that’s View > Developer > Developer Tools. In the command line at the bottom of the developer console, paste the get.js code and hit enter. (this could take a few minutes.) In the new tab, copy the text and paste it in users.txt.

Edit twitter_mute_unmute.py

    # Depends on the environment
    driver_path = '/usr/bin/chromedriver'
    
    username = 'YOUR USERNAME'
    password = 'YOUR PASSWORD'
    
    # Comment out/in    
    Twitter().mute() # When want to mute
    # Twitter().unmute() # When want to unmute

Run

$ ls
twitter_mute_unmute.py users.txt

$ python3 twitter_mute_unmute.py

get.js

var objs = document.getElementsByClassName('js-user-profile-link account-group');
var body = '';

Array.from(objs).slice(0, -1).forEach((o, i) => {
  var id = o.getAttribute('href').slice(1);
  body += `${id}<br>`;
})

var html = `${body}`;

var wnd = window.open("about:blank", "");
wnd.document.write(html);
wnd.document.close();

twitter_mute_unmute.py

#!/usr/bin/env python3
# -*- coding: utf-8 -*-


import random
import time
from selenium import webdriver


class Browser:

    def __init__(self):
        opt = webdriver.chrome.options.Options()
        opt.add_argument('--headless')
        self.driver = webdriver.Chrome(
                executable_path=driver_path,
                chrome_options=opt,
                )

    def __del__(self):
        self.driver.quit()


class Twitter(Browser):

    def __init__(self):
        super(Twitter, self).__init__()

    def login(self):
        self.driver.get("https://twitter.com/login")
        username_field = self.driver.find_element_by_class_name("js-username-field")
        password_field = self.driver.find_element_by_class_name("js-password-field")
        username_field.send_keys(username)
        password_field.send_keys(password)
        self.driver.find_element_by_class_name("EdgeButtom--medium").click()

    def create_urls(self):
        with open(users_path, 'r') as f:
            urls = ['https://twitter.com/' + user.rstrip()
                    for user in f.readlines()]
        return urls

    def mute(self):
        self._mute_unmute('mute')

    def unmute(self):
        self._mute_unmute('unmute')

    def _mute_unmute(self, which):
        self.login()
        for url in self.create_urls():
            self.driver.get(url)
            self.random_sleep()
            try:
                self.driver.find_element_by_xpath(
                        '//button[@class="user-dropdown dropdown-toggle js-dropdown-toggle js-link js-tooltip btn plain-btn"]'
                        ).click()

                if which == 'mute':
                    self.driver.find_element_by_xpath(
                            '//li[@class="mute-user-item"]/button'
                            ).click()
                elif which == 'unmute':
                    self.driver.find_element_by_xpath(
                            '//li[@class="unmute-user-item"]/button'
                            ).click()
            except:
                continue

    def random_sleep(self):
        # [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5]
        seconds =  [0.5*x for x in range(1, 8)]
        second = random.choice(seconds)
        time.sleep(second)


if __name__ == '__main__':

    global driver_path,users_path, username, password

    # Chromedriver path
    driver_path = '/usr/bin/chromedriver'
    # Target users path
    users_path = 'users.txt'
    # Twitter username
    username = ''
    # Twitter password
    password = ''

    Twitter().mute()
    # Twitter().unmute()

users.txt

Twitter
TwitterMediaJP
TwitterSportsJP
TwitterTVJP