Python Selenium geckodriver print silently breaks printing - python

I have searched and tried different things for days and I came up empty handed. The code is fairly straight forward.
from selenium import webdriver
import os
downloadfolder = os.path.join(os.path.expanduser("~/"),"mydownload")
os.chdir(downloadfolder)
profile = webdriver.FirefoxProfile(downloadfolder)
profile.set_preference('print.always_print_silent',True)
profile.set_preference('print_printer','Print to File')
profile.set_preference('print.print_to_filename',
os.path.join(downloadfolder,'print.pdf'))
driver.webdriver.Firefox(profile)
driver.get("https://www.google.com") # or whatever site
driver.execute_script("window.print();")
This setup used to work, up to about a week ago, when I have noticed I am not getting the screen print.
When I try to print manually, I will get "An error occurred while printing".
What I have noticed in "about:config" on Firefox is that when I hit print, it will defaults to "PostScript/default". And no matter what I set it to, it will default to this value the moment I click on print.
Another thing that got me scratching my head. This does not happen if I don't set
profile.set_preference('print.always_print_silent',True)
But the dialog box shows. Any help appreciated.

Related

python: selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: invalid locator

I wanted to write a python code on python 3.10 with selenium to automize the loging in my gmail account. There is something false with Xpath.
The Error that I am getting is selenium.common.exceptions.InvalidArgumentException: Message: invalid argument: invalid locator
Below is my code
from selenium.webdriver.chrome.service import Service
import time
browser = webdriver.Chrome(service=Service("C:/Users/user/Desktop/chromedriver.exe"))
browser.get("https://www.google.de/")
browser.fullscreen_window()
time.sleep(1)
login = browser.find_element("By.XPATH", "//*[#id='gb']/div/div[1]/div/div[1]/a")
login.click()
time.sleep(2)
browser.quit()```
I tried to change the Xpath but it didn't work. I thought that is something false with selenium code then I uninstalled the selenium and installed it again but it didn't work.
Newcomer...
Google first. Selenium has been industry standard since I remember, this has been posted in THOUSAND sites.
In short, "By.XPATH" is pretty wrong. You pass a string there, you has to pass the function.
So, go back to google (or even here- search ...), and find how to import By function in selenium (like you did with selenium) then pass the method like login = browser.find_element(By.XPATH, "//*[#id='gb']/div/div[1]/div/div[1]/a") and you'll fine.
Remember this after ask very common questions like this, you have THOUSAND of lines examples of everything in google. Spend your time reading.
Remove the double quotes in By.XPATH -
browser.find_element(By.XPATH, "//*[#id='gb']/div/div[1]/div/div[1]/a")
and import By:
from selenium.webdriver.common.by import By

execute_script don't work with Youtube Search : Selenium Python

so I'm fairly new to python but I start to understand how things work together, however for this problem I didn't find any solution.
So my problem is I'm making a simple bot with python that can open Youtube and search for specific keywords, Now I have tried the send.keys method and it won't work because I want to use special characters that ChromeWebDriver just can't send due to chromedriver only supports characters in the bmp Problem!
So then I explored my options 1 using GeckoDriver Firefox instead and yeah it worked! however, I couldn't make Firefox undetected as a bot!
option 2 is using the execute_script method with ChromeWebDriver it did work at first with Google search, But then I wanted to use it for Youtube and nothing happens.
I run my script browser works youtube page is loaded but nothing happens the script completes the 20s sleep and exists normally but no input has been made in the search bar or any error in my console just nothing!
maybe the element is not loaded? but I put 20sec sleep after each line of code to make sure the page have enough time to load properly I tried to use Find_by_id | xPath | class_name still nothing
I tried to check if the element is there before executing the input text line and still nothing
Also, I have tried to .click the element before doing text input the search bar is highlighted the click worked but still no text and nothing.
As for the characters I'm trying to input into the search bar are like this: 𝕊 𝕄
which can't be sent by the send.key method
My code:
import undetected_chromedriver.v2 as uc
from time import sleep
import jdk
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
if __name__ == '__main__':
driver = uc.Chrome()
driver.get('https://youtube.com')
sleep(20)
driver.execute_script("document.getElementById('search').checked = true;")
print('Searching for Element')
sleep(20)
Elem_nt = driver.find_element(By.XPATH, "/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form")
print('Finding Element Now...')
sleep(20)
driver.find_element(By.XPATH, "/html/body/ytd-app/div/div/ytd-masthead/div[3]/div[2]/ytd-searchbox/form").click()
print('Clickling Element Now')
sleep(20)
driver.execute_script("arguments[0].value = 'vid_title';", Elem_nt)
print('input Text Now')
sleep(20)
Any help would be appreciated, also excuse the terms that I use to explain as I'm new to this I just want to explain everything.
Try this one
import pyperclip
from selenium.webdriver.common.keys import Keys
pyperclip.copy(your_text)
element = driver.find_element(By.CLASS_NAME,"your_class_name")
element.send_keys(Keys.CONTROL + "V")

Why do I get "webbrowser.Error: could not locate runnable browser"?

I'm new to coding in python and I'm wondering if some one can explain why this code works on the second try but not on the first?
I was just trying to open a browser that was not the default one.
first try --> did not work
import webbrowser
url='https://www.mozilla.org'
webbrowser.register('firefox', None)
webbrowser.BackgroundBrowser("C:\\Program Files\\Mozilla Firefox\\firefox.exe")
webbrowser.get('firefox').open(url)
webbrowser.Error: could not locate runnable browser
Process finished with exit code 1
second try --> works
import webbrowser
url='https://www.mozilla.org'
webbrowser.register('firefox', None, webbrowser.BackgroundBrowser("C:\\Program Files\\Mozilla Firefox\\firefox.exe"))
webbrowser.get('firefox').open(url)
Process finished with exit code 0
Like you can see here, register tells Python where the webbrowser with the name "firefox" can be found. You have to pass an instance (BackgroundBrowser) or a constructor. In the first code snippet you pass None as the constructor, which is not a valid browser class, it can thus not find/create the browser and cannot register it. In the second snippet you pass your BackgroundBrowser instance and thus it can register this valid browser as "firefox" and you can run it later.
The 5th line (webbrowser.BackgroundBrowser...) in the first snippet does basically nothing, you are supposed to give that as an argument to register like you do in the second snippet.

Selenium Python throwing browser_switcher_service.cc(238) error for no reason

I wrote a pretty simple script to ping a website -> find an element by name -> check if it's displayed or not. The script seems to be working fine but throwing a weird error at the same time.
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
import time
# Chrome
driver = webdriver.Chrome(executable_path='D:/selenium_drivers/chromedriver.exe')
driver.get("http://newtours.demoaut.com/")
element = driver.find_element_by_name('userName')
print(element.is_displayed()) # T/F based on element's state
Here is the output from this script,
I get the output as True which is great, but it comes along with this error for reasons I can't quite comprehend at the moment.
[12080:16948:0505/181346.157:ERROR:browser_switcher_service.cc(238)] XXX Init()
Google Chrome Version: 81.0.4044.129 (64-bit)
Selenium Chromedriver Version: 81.0.4044.69
Operating System: Windows 10
I am not sure what the purpose of this call is; but it appears to be a harmless logging call. The relavant code is:
void BrowserSwitcherService::Init() {
LOG(ERROR) << "XXX Init()";
LoadRulesFromPrefs();
StartDownload(fetch_delay());
}
Which was added in this commit. Does this do anything? Or just print a message to the console? Are any Python errors raised?

Python Selenium Code behaving differently depending on calling mode

I've tripped on a very easy to reproduce code that's driving me crazy.
I'm trying to take a picture of the screen after entering a container code in a website form, using Python and PhantomJS webdriver (selenium).
The code that makes it possible is quite short, and reproducing it in the console works fine. But if this same code is within a function or a script, it doesn't behave the same.
Here is the working code, that works for me writing it line by line in the console:
(Python version 2.7.9, selenium 2.53.6)
> python
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.set_window_size(1280, 1024)
driver.get('http://www.track-trace.com/container')
driver.find_element_by_name('number').clear()
driver.find_element_by_name('number').send_keys('CGMU5109933')
driver.find_element_by_xpath('//input[#name="commit" and #value="Track direct"]').click()
driver.save_screenshot('./x.png')
However, this same code inside a function or a script only behaves the same until it reaches the click.
It freezes while loading, and the screenshot shows just that.
It doesn't matter what type of wait I try, implicit or explicit, the loading button won't end.
Here is the same code inside a function in foo.py module to make trying it easier.
The picture that is taken won't match the picture taken by the above code.
# foo.py
from selenium import webdriver
def try_it():
driver = webdriver.PhantomJS()
driver.set_window_size(1280, 1024)
driver.get('http://www.track-trace.com/container')
driver.find_element_by_name('number').clear()
driver.find_element_by_name('number').send_keys('CGMU5109933')
driver.find_element_by_xpath('//input[#name="commit" and #value="Track direct"]').click()
driver.save_screenshot('./x.png')
> python
>>> import foo
>>> foo.try_it()
The code must be in a function as it is called on demand when new search petitions arrive on a web service that is integrated in an application.
I always seek first for questions that may have valid answers but this time it doesn't seem to be anything similar to my problem.
Any idea why this may be happening and how to avoid it would be very much appreciated. If any other code or clarification is needed don't hesitate to ask.
This is purely a timing issue. Button clicks don't block, meaning once a click is issued, it returns and python runs the very next line right away. You need to wait until the next page has finished loading before you can take the screenshot. I would use an explicit wait that blocks until an element on the next page you're interested in has loaded. Likewise, I think you do need to worry about the popup asking if you really want to use direct.
My script:
from explicit import waiter
from selenium import webdriver
from selenium.webdriver.common.by import By
def locate_container(driver, container_id):
url = 'http://www.track-trace.com/container'
track_direct_xpath = '//input[#name="commit" and #value="Track direct"]'
im_sure_css = 'div.modal-footer button.jq-directinfo-continue'
tracking_details_header_css = 'div#wrapper > div.inner > h1'
# Load the container search page
driver.get(url)
# Locate the container field, enter container_id, click direct search button
waiter.find_write(driver, 'number', container_id, clear_first=True, by=By.NAME)
waiter.find_element(driver, track_direct_xpath, By.XPATH).click()
# Locate I'm Sure button and click it
waiter.find_element(driver, im_sure_css, By.CSS_SELECTOR).click()
# Wait for the "Tracking details for Container: XXX" header to load
waiter.find_element(driver, tracking_details_header_css, By.CSS_SELECTOR)
# Now we know the page has loaded and we can take the screenshot:
driver.save_screenshot('./x.png')
def main():
driver = webdriver.PhantomJS()
try:
driver.set_window_size(1280, 1024)
locate_container(driver, 'CGMU5109933')
finally:
driver.quit()
if __name__ == "__main__":
main()
(Full disclosure: I maintain the explicit package, which is meant to simplify using explicit waits. You can replace it with direct waits and get the same affect. Simply pip install explicit to install)

Categories

Resources