Selenium+Python Youtube close driver after video finish playing - python

Hi I am trying to play YouTube using selenium and python. its easy to get played, but i got trouble to close driver after video finish playing. I have tried my script to get text but not really working.
while True:
try:
element = WebDriverWait(driver, 6).until(
EC.presence_of_element_located((By.XPATH, "//*[contains(text(),'My Video title')]"))
)
except:
break
driver.close()
driver.quit()
code above is to close after video title is change, but only working when i refresh the page. May be somebody can help with this code or may have another elegant method to do the job

You could force it to quit using the exit function of the os library os.exit(0)
(for alternatives to os.exit(0) see geeks for geeks python exit commands), but that would terminate the entire program which I am not quite sure that you want to do.

Related

Selenium Generated User Dialog

I have a selenium script that runs a loop on a process that prints text into my python IDLE to get a list of data, which I then copy and paste to excel - which is great. But not optimal.
I am currently using sleep at the start of the loop to give me time to change parameters on my trading view strategy tester, which gives me a different result to be printed as intended. However, I would like more or less time on most occasions. Waiting for the path to change does not work as the path never changes, it just gets looped again with a different text output based on the changes I would have made manually on the strategy settings.
Also worth noting that I am using firefox geckobrowser as opposed to chrome and that the purpose of the script is to automate a tedious manual task of data collection.
Is it at all possible to create a pop-up button or something of the like via selenium that says "Next" for example, that I can click and let the script know its okay for the loop to continue? Can I simply replace sleep with click "Next" or something of the like for example?
for i in range(20):
time.sleep(10)
netProfit = driver.find_element("xpath", '/html/body/div[2]/div[7]/div[2]/div[4]/div/div[2]/div/div[1]/div[1]/div[2]/div[2]')
numberTrades = driver.find_element("xpath", '/html/body/div[2]/div[7]/div[2]/div[4]/div/div[2]/div/div[1]/div[2]/div[2]')
winRate = driver.find_element("xpath", '/html/body/div[2]/div[7]/div[2]/div[4]/div/div[2]/div/div[1]/div[3]/div[2]')
print(netProfit.text, numberTrades.text, winRate.text)
This works for now, but it's a pain waiting for timer on occasions I don't need it and even more of a pain on occasions when it's not enough time.
I am expecting something like this to replace time.sleep(10)
WebDriverWait(driver, 180).until("Next" button is clicked)
Ideally I would like a solution that can be done in selenium as my experience is limited, but any workarounds would be appreciated all the same.

How to use selenium to navigate web pages with multiple drop downs and check boxes

I am trying to automate a process to download data from a website. The code works if I run it step by step but if I run it all at once it fails. Giving the error
ElementNotInteractableException: Message: element not interactable
I have got around this using time.sleep(x amount of time) but it still seems to fail intermittently. I am having trouble implementing implicit waits. Any help would be appreciated. Code below.
import selenium
browser = webdriver.Chrome(executable_path=r'path\to\chromedriver.exe')
browser.get("https://map.sarig.sa.gov.au/")
browser.maximize_window()
browser.switch_to.frame(browser.find_element_by_id('MapViewer'))
browser.find_element_by_xpath('//*[#id="TourWidget"]/div[1]/span').click()
browser.find_element_by_xpath('//*[#id="menuAllMapLayers"]/div[2]/p').click()
browser.find_element_by_xpath('//*[#id="238"]/li[1]/div/div/span[1]').click()
time.sleep(3)
browser.find_element_by_xpath('//*[#id="238"]/li[1]/div/div/span[1]').click()
browser.find_element_by_xpath('//*[#id="238"]/li[3]/div/div/label/span').click()
browser.find_element_by_xpath('//*[#id="239"]/li[1]/div/div/span[1]').click()
browser.find_element_by_xpath('//*[#id="239"]/li[3]/div/div/label/span').click()
browser.find_element_by_xpath('//*[#id="menuActiveLayers"]').click()
browser.find_element_by_xpath('//*[#id="groupOptions238"]/span').click()
time.sleep(3)
browser.find_element_by_xpath('//*[#id="238"]/li[2]/div/div[3]/div[2]/span').click()
browser.find_element_by_xpath('//*[#id="groupOptions239"]/span').click()
time.sleep(3)
browser.find_element_by_xpath('//*[#id="239"]/li[2]/div/div[3]/div[2]/span').click()
Use ActionChains and get access to pause(3) instead of using sleep(3) but it could also help to use Waits and checking if your elements actually are "visible" rather than "present" (see expected_conditions)
It's a lot of dropdowns so maybe there are not visible all the time, but you can run these checks after doing a move_to_element() so it would actually be present.

How do I make this python automation code using Pyautogui faster and safer?

This is a code that I use to register my courses for semester. I want this code to run fastest as possible so that I can select my preferred courses faster than other students who select them manually, the seats and section of desired classes fill-up fast. My concern is that if my code runs faster and the browser cant keep up with it then it will cause issue. For example I will be running on google chrome browser. And what should I change to make this code faster without risking Thanks in advance.
import pyautogui
import time
import webbrowser
pyautogui.FAILSAFE = False
time.sleep(1)
pyautogui.hotkey('alt', 'tab')
##Subject choose
time.sleep(0.5)
pyautogui.hotkey('ctrl', 'f')
pyautogui.write('PHY182.1')
pyautogui.press('enter')
pyautogui.press('esc')
pyautogui.hotkey('shift', 'tab')
pyautogui.press('space')
I did something similar I while ago, not exactly your case but I believe it would help. If you want it to be as fast as possible while making sure that the browser if keeping up with you, you should make your script recognize that the page you are going to be on has fully loaded, for this I would use selenium, so when the page is fully loaded it does the thing really fast, but not before. I think that if you did it like that it would work.
You have to setup selenium first, it's a bit long so I won't explain here, I'll just give you an example of it being used.
Selenium example:
driver.maximize_window()
driver.get(url) # goes to url and waits till it's loaded #
einput = driver.find_element_by_id("identifierId") # find the element you want through it's name #
einput.send_keys(email) # what you want to write #
einput.send_keys(Keys.RETURN) # enter #
I used this code for a script I made that logged people into google really fast in incognito. But I believe you could adapt it to your case. It's not perfect though because some pages 'never finish loading' but give it a try.

how to work with code when web driver is open

ok; I wrote a code and use python selenium and then with pyqt5 made it graphical.
but when I push the button start webdriver opened and I can't access to my windows's code any more, It got frozen , but I should input some valuable or click on some button as the code running.
what should I do ?
I've faced the same problem before. My solution was to use the time.sleep(duration) when the web driver opened the Window. For your specific situation, I think that you can use javascript on the page to check the user input is complete or not. Once the input fields are filled then trigger the process behind.
What I did was using a Process, so it would seperate the GUI-Loop and everything what is being done by selenium in a Process. By doing so you'll be able to use your GUI parallel to running Selenium in the Background by your process.

WhatsApp Web automation with Selenium not working

I found this python script on github that sends automatic WhatsApp Web messages through Selenium.
#https://www.github.com/iamnosa
#Let's import the Selenium package
from selenium import webdriver
#Let's use Firefox as our browser
web = webdriver.Firefox()
web.get('http://web.whatsapp.com')
input()
#Replace Mr Kelvin with the name of your friend to spam
elem = web.find_element_by_xpath('//span[contains(text(),"Mr Kelvin")]')
elem.click()
elem1 = web.find_elements_by_class_name('input')
while True:
elem1[1].send_keys('hahahahahahaha')
web.find_element_by_class_name('send-container').click()
Even though it was meant for spamming, I was trying to adapt it for a good purpose, but the script as it stands doesn't seem to work. Instead of sending a message through WhatsApp Web, it simply loads a QR authentication screen and then it does nothing after I authenticate with my cellphone.
Any clue as to why this is happening? I'm running the lastest version of Selenium WebDriver on Firefox and geckodriver has already been extracted to /usr/bin/.
I realise this post is older, but it still seems to be frequently looked at.
The keystroke explanation of #vhad01 makes sense but did not work for me.
A simple dirty workaround that worked for me:
Replace input() with
import time
time.sleep(25)
while 25 is the amount of seconds it will be waited until the code will be further executed. (15 should also be sufficient to scan the QR code,...).
The way I implement the scanning of the QR code is by detecting if the search bar is present or not on the page.
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
chatlist_search = ".jN-F5.copyable-text.selectable-text"
web.get("https://web.whatsapp.com")
WebDriverWait(web, 60).until(EC.visibility_of_element_located((By.CSS_SELECTOR, chatlist_search)))
This would wait until the chat search-bar is rendered on the page, or it will timeout in 60 seconds.
This line :
input()
is waiting for a keystroke to continue.
Simply press any key after scanning.
I was writing a selenium script to schedule my msgs and I came across your question. Yes, problem is that input() line.
Instead of using input():
Use time.sleep(), no doubt it will work but better approach it to use implicit_wait(15)
Time.sleep() makes you wait even after scanning. The script totally stops till the given seconds.
In implicit_wait() the if element appear before specified time than script will start executing otherwise script will throw NoSuchElementException.
I used a more different method to whatsapp_login() and QR scanning. To see that my repo link: https://github.com/shauryauppal/PyWhatsapp
You would like this approach too.
A better way is to scan the QR code hit return in the command line and the proceed further on your code.
browser = webdriver.Firefox()
browser.get('https://web.whatsapp.com/')
print('Please Scan the QR Code and press enter')
input()
This is all you need and is also not very vague logic to apply to this problem.

Categories

Resources