📜  在Python使用Selenium转发推文

📅  最后修改于: 2022-05-13 01:55:38.592000             🧑  作者: Mango

在Python使用Selenium转发推文

先决条件:

  • Selenium驱动程序。
  • Web 驱动程序方法
  • 在网页中定位元素的方法

在本文中,我们将了解如何转发特定主题标签并决定是否将其显示在 Twitter 的“趋势”部分。我们可以在 Twitter 上自动化一个帐户,以转发与任何特定主题标签相关的所有推文。这可以在Python使用Selenium来实现。

注意:您可以从这里下载 webdriver。

分步实施:

第 1 步:导入所需的模块

Python3
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import getpass


Python3
driver = webdriver.Chrome(executable_path='/usr/lib/chromium-browser/chromedriver')


Python3
driver.get('https://twitter.com/login')
driver.maximize_window()


Python3
username = input('Enter Your Username: ')
password = getpass.getpass(prompt = 'Enter Your Password: ')
 
# locating the input box for username
u = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div[2]/form/div/div[1]/label/div/div[2]/div/input')
u.send_keys(''+str(username)+'')
 
# locating the input box for password
p = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]/\
main/div/div/div[2]/form/div/div[2]/label/div/div[2]/div/input')
p.send_keys(''+str(password)+'')


Python3
driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div[2]/form/div/div[3]/div').click()
time.sleep(10)


Python3
srch = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div/div[2]/div/div[2]/div/div/div/div[1]/div/div/div\
/form/div[1]/div/label/div[2]/div/input')
 
s = input('Enter the Hashtag you want to retweet: ')
srch.send_keys('#'+str(s)+'')
srch.send_keys(Keys.ENTER)


Python3
c = int(input('Max no. of Retweets: '))
driver.implicitly_wait(5)
driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div/div[1]/div/div[1]/div[2]/nav/div/div[2]/div/div[2]/a').click()
time.sleep(10)


Python3
while(1):
   
      # waiting for the webpage to load
    time.sleep(5)
    rt=driver.find_elements_by_css_selector('.css-18t94o4[data-testid ="retweet"]')
    for r in rt:
        try:
            r.click()
            time.sleep(2)
            driver.find_element_by_xpath('//*[@id="layers"]\
            /div[2]/div/div/div/div[2]/div[3]/div/div/div/div').click()
             
            c -= 1
            time.sleep(2)
            if(c == 0):
                break
        except (ElementClickInterceptedException, StaleElementReferenceException):
            pass
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
    if(c == 0):
        break


Python3
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import getpass
 
# initializing the driver
driver = webdriver.Chrome(
  executable_path='/usr/lib/chromium-browser/chromedriver')
 
# directing to the twitter login page
driver.get('https://twitter.com/login')
driver.maximize_window()
 
# asking the user for username and pas
username = input('Enter Your Username: ')
password = getpass.getpass(prompt='Enter Your Password: ')
 
# locating the input box for username
u = driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div[2]/form/div/div[1]\
/label/div/div[2]/div/input')
 
# inputing the username
u.send_keys(''+str(username)+'')
 
# locating the input box for password
p = driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div[2]/form/div/div[2]\
/label/div/div[2]/div/input')
 
# inputing the password
p.send_keys(''+str(password)+'')
print("loading... \n")
time.sleep(3)
 
# logging in
driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div[2]/form/div/div[3]/div').click()
time.sleep(10)
 
# Locating the search box
srch=driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div/div[2]/div/div[2]\
/div/div/div/div[1]/div/div/div/form/div[1]\
/div/label/div[2]/div/input')
 
# inputing the hashtag to retweet
s = input('Enter the Hashtag you want to retweet: ')
 
# inputing the hashtag
srch.send_keys('#'+str(s)+'')
 
# searching for the hashtag
srch.send_keys(Keys.ENTER)
 
# inputing maximum number of tweets one wants to retweet
c=int(input('Max no. of Retweets: '))
driver.implicitly_wait(5)
 
# directing the most latest tweets
driver.find_element_by_xpath('//*[@id="react-root"]/div/\
div/div[2]/main/div/div/div/div[1]/div/div[1]/div[2]/\
nav/div/div[2]/div/div[2]/a').click()
time.sleep(10)
 
 
while(1):
    time.sleep(5)
     
    # locating the retweet option in the webpage
    rt = driver.find_elements_by_css_selector(
      '.css-18t94o4[data-testid ="retweet"]')
    for r in rt:
        try:
               
            # retweeting
            r.click()
            time.sleep(2)
             
            # toggling the confirmation to retweet
            driver.find_element_by_xpath('//*[@id="layers"]/div[2]\
            /div/div/div/div[2]/div[3]/div/div/div/div').click()
            c -= 1
            time.sleep(2)
            if(c==0):
                break # breaking from the retweet loop
        except (ElementClickInterceptedException, StaleElementReferenceException):
            pass
           
     # scrolling to the bottom of the page
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
     
     # max number of retweets are achieved
    if(c==0):
        break # breaking from the retweet loop
driver.close()



步骤 2执行 webdriver 并将其分配给可变驱动程序。

蟒蛇3

driver = webdriver.Chrome(executable_path='/usr/lib/chromium-browser/chromedriver')


第 3 步:定向到所需的 URL 并使用 maximize_window 最大化窗口。

蟒蛇3

driver.get('https://twitter.com/login')
driver.maximize_window()


第 4 步:向用户询问 Twitter 帐户凭据,并通过路径找到它们,将它们发送到用户名和密码输入框。使用 getpass 输入密码以提高安全性。您可以在所需位置插入凭据 send_keys() 。



蟒蛇3

username = input('Enter Your Username: ')
password = getpass.getpass(prompt = 'Enter Your Password: ')
 
# locating the input box for username
u = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div[2]/form/div/div[1]/label/div/div[2]/div/input')
u.send_keys(''+str(username)+'')
 
# locating the input box for password
p = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]/\
main/div/div/div[2]/form/div/div[2]/label/div/div[2]/div/input')
p.send_keys(''+str(password)+'')


第五步:通过XPath找到登录按钮,点击click()。此外,使用以前使用的相同方法等待网页加载。

蟒蛇3

driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div[2]/form/div/div[3]/div').click()
time.sleep(10)


步骤 6.询问用户要转发的主题标签,并使用 xpath 和 send_keys() 将其插入搜索框,如前所述。

蟒蛇3

srch = driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div/div[2]/div/div[2]/div/div/div/div[1]/div/div/div\
/form/div[1]/div/label/div[2]/div/input')
 
s = input('Enter the Hashtag you want to retweet: ')
srch.send_keys('#'+str(s)+'')
srch.send_keys(Keys.ENTER)


第 7 步:询问用户想要进行的最大转发次数,并使用 xpath 定向到最新的推文部分。另外,使用 time.sleep() 等待网页加载。

蟒蛇3



c = int(input('Max no. of Retweets: '))
driver.implicitly_wait(5)
driver.find_element_by_xpath('//*[@id="react-root"]/div/div/div[2]\
/main/div/div/div/div[1]/div/div[1]/div[2]/nav/div/div[2]/div/div[2]/a').click()
time.sleep(10)

第 8 步:启动一个 while 循环,当达到最大转发次数时该循环中断。在循环内,找到所有转发按钮(使用以前的方法)并一个一个点击它们。

蟒蛇3

while(1):
   
      # waiting for the webpage to load
    time.sleep(5)
    rt=driver.find_elements_by_css_selector('.css-18t94o4[data-testid ="retweet"]')
    for r in rt:
        try:
            r.click()
            time.sleep(2)
            driver.find_element_by_xpath('//*[@id="layers"]\
            /div[2]/div/div/div/div[2]/div[3]/div/div/div/div').click()
             
            c -= 1
            time.sleep(2)
            if(c == 0):
                break
        except (ElementClickInterceptedException, StaleElementReferenceException):
            pass
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
    if(c == 0):
        break

下面是完整的实现:

蟒蛇3

from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.support.ui import WebDriverWait
import time
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import ElementClickInterceptedException
from selenium.common.exceptions import StaleElementReferenceException
from selenium.webdriver.common.keys import Keys
from selenium.webdriver import ActionChains
import getpass
 
# initializing the driver
driver = webdriver.Chrome(
  executable_path='/usr/lib/chromium-browser/chromedriver')
 
# directing to the twitter login page
driver.get('https://twitter.com/login')
driver.maximize_window()
 
# asking the user for username and pas
username = input('Enter Your Username: ')
password = getpass.getpass(prompt='Enter Your Password: ')
 
# locating the input box for username
u = driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div[2]/form/div/div[1]\
/label/div/div[2]/div/input')
 
# inputing the username
u.send_keys(''+str(username)+'')
 
# locating the input box for password
p = driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div[2]/form/div/div[2]\
/label/div/div[2]/div/input')
 
# inputing the password
p.send_keys(''+str(password)+'')
print("loading... \n")
time.sleep(3)
 
# logging in
driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div[2]/form/div/div[3]/div').click()
time.sleep(10)
 
# Locating the search box
srch=driver.find_element_by_xpath('//*[@id="react-root"]\
/div/div/div[2]/main/div/div/div/div[2]/div/div[2]\
/div/div/div/div[1]/div/div/div/form/div[1]\
/div/label/div[2]/div/input')
 
# inputing the hashtag to retweet
s = input('Enter the Hashtag you want to retweet: ')
 
# inputing the hashtag
srch.send_keys('#'+str(s)+'')
 
# searching for the hashtag
srch.send_keys(Keys.ENTER)
 
# inputing maximum number of tweets one wants to retweet
c=int(input('Max no. of Retweets: '))
driver.implicitly_wait(5)
 
# directing the most latest tweets
driver.find_element_by_xpath('//*[@id="react-root"]/div/\
div/div[2]/main/div/div/div/div[1]/div/div[1]/div[2]/\
nav/div/div[2]/div/div[2]/a').click()
time.sleep(10)
 
 
while(1):
    time.sleep(5)
     
    # locating the retweet option in the webpage
    rt = driver.find_elements_by_css_selector(
      '.css-18t94o4[data-testid ="retweet"]')
    for r in rt:
        try:
               
            # retweeting
            r.click()
            time.sleep(2)
             
            # toggling the confirmation to retweet
            driver.find_element_by_xpath('//*[@id="layers"]/div[2]\
            /div/div/div/div[2]/div[3]/div/div/div/div').click()
            c -= 1
            time.sleep(2)
            if(c==0):
                break # breaking from the retweet loop
        except (ElementClickInterceptedException, StaleElementReferenceException):
            pass
           
     # scrolling to the bottom of the page
    driver.execute_script("window.scrollTo(0,document.body.scrollHeight)")
     
     # max number of retweets are achieved
    if(c==0):
        break # breaking from the retweet loop
driver.close()

输出: