-1

I'm trying to create a tool that will automate the process of sharing video across multiple platforms and social media. I wanted to use Python and Selenium as a Webdriver to click on the share button on the YouTube video's webpage and then post it on several social media.

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait, Select
from selenium.webdriver.support import expected_conditions
from main import wait_for_element
import time
import os

options = webdriver.ChromeOptions()
options.add_argument("--user-data-dir=PATH_2_CHROME_DATA")

browser = webdriver.Chrome(options=options, executable_path='PATH_2_CHROMEDRIVER.EXE')

def wait_for_element(browser, element, by_what):
    return WebDriverWait(browser, 10).until(expected_conditions.presence_of_element_located((by_what, element)))

def youtube(youtube_details):
    yt_url = youtube_details['yt_url']
    # YouTube Page
    browser.get(yt_url)

    share_btn = wait_for_element(browser,'//*[@id="button" and contains(@aria-label,"Share")]',By.XPATH)
    share_btn.click()

    reddit_btn = wait_for_element(browser,'//*[@id="target" and contains(@title,"reddit")]', By.XPATH)
    reddit_btn.click()

    community_dropdown = wait_for_element(browser,'#SHORTCUT_FOCUSABLE_DIV > div > div > div > div.s7pq5uy-1.hjrnH > div.s7pq5uy-5.ezjCpv > div.sdccme-0.kIpPAE > div > div.s1eg75c7-1.dsiNBS > div > div > div.s1u2j4lv-1.bTtqCO > input', By.CSS_SELECTOR)
    community_dropdown.send_keys('r/Bumble')                  

if __name__ == '__main__':
    youtube_details = {
        'yt_url':'https://www.youtube.com/watch?v=dQw4w9WgXcQ',
    }
    youtube(youtube_details)

When the Webdriver click on the reddit share button, it opens a new tab which the driver isn't controlling. Thus, the driver could not locate the element on reddit webpage.

I tried adding the following line after clicking on the reddit share button to switch to the newly opened tab.

browser.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

But it isn't working. I've also looked through several forum posts but none of which is exactly the problem I'm facing.

5Volts
  • 179
  • 3
  • 13
  • Possible duplicate of [Handle multiple windows in Python](https://stackoverflow.com/questions/10629815/handle-multiple-windows-in-python) – JeffC Feb 07 '19 at 21:39

2 Answers2

3

chromedriver generates window handle for each tab, use it to switch between the tabs as you switch between windows

driver.switch_to.window(driver.window_handles[-1])
Guy
  • 46,488
  • 10
  • 44
  • 88
0

I use driver.switch_to_window to switch to a newly opened tab, and then back again.

Basically, I keep track of driver.window_handles before I do the action (e.g., button click), which opens the new tab.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574