How to open a url using an adress of an application - python

How to open a URL without webbrowser using Python, but with an address of the application with which I want to open it.

There are three ways to do this
Case 1: You just need to open a page. and that is it,
import webbrowser
webbrowser.open("https://yoursite.com")
The above will open https://yoursite.com on your default browser
Case 2: You need to open, as well as do a task eg refresh
from selenium import webdriver
import time
driver = webdriver.Edge("path to your edge driver")
driver.get("https://yoursite.com")
# The command below will refresh your webbrowser after 3 seconds of opening it
time.sleep(3)
driver.refresh()
If you want to use chrome... use driver = webdriver.Chrome("path to your chrome driver")
Case 3:You have already opened your webbrowser (via selenium) and you are in another program and you want to see it without opening it manually
from selenium import webdriver
import time
driver = webdriver.Edge("path to your edge driver")
driver.get("https://yoursite.com")
time.sleep(10)
# this command stores your webbrowser window in a variable
main_page = driver.current_window_handle
# this command moves the webbrowser to the front
driver.switch_to.window(main_page)
Also you have to install a driver for your browser if you are using the selenium thing...
For edge go to https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/#:~:text=Microsoft%20Edge%20WebDriver%20for%20Microsoft%20Edge%20will%20work,find%20your%20correct%20build%20number%3A%20Launch%20Microsoft%20Edge. and choose your edge version...
And for chrome go to https://chromedriver.chromium.org/downloads
You will also have to do pip install selenium in the terminal...
Hope this helps ;)

Try selenium, although you'll have to first download Chromedriver:
from selenium import webdriver from selenium.webdriver.common.keys import Keys
driver = webdriver.Firefox() driver.get("http://stackoverflow.com/")
body = driver.find_element_by_tag_name("body") body.send_keys(Keys.CONTROL + 't')
driver.close()

Related

Opening a new unfocused tab in Chrome or Firefox with Python on Windows OS

My OS → Microsoft Windows 11
GOOGLE CHROME:
I have Google website open and I want to open the Stack Overflow website in a new tab but the screen keeps showing the Google website, like this:
My first attempt was trying it with the webbrowser module and its autoraise argument:
sof = 'https://stackoverflow.com'
webbrowser.open(sof, new=0, autoraise=False)
webbrowser.open(sof, new=2, autoraise=False)
webbrowser.open_new_tab(sof)
None of the above options caused the tab in Chrome to open in the background keeping focus on the tab that was already open.
So I went for another try using subprocess and its getoutput function:
r = subprocess.getoutput(f"google-chrome-stable https://stackoverflow.com")
r
That option didn't even open a new tab in my browser.
MOZILLA FIREFOX:
My attempt was trying it with the webbrowser module and its autoraise argument (As my default browser is different I need to set the browser):
sof = 'https://stackoverflow.com'
webbrowser.register('firefox',
None,
webbrowser.BackgroundBrowser("C://Program Files//Mozilla Firefox//firefox.exe"))
webbrowser.get('firefox').open(sof, new=0, autoraise=False)
In neither of the two I managed to make this functionality work.
How should I proceed?
Chrome:
I don't think it is feasible (at least not w/ chrome).
See this StackExchange answer for details. Especially the mentioned bug that most likely will never get fixed.
Firefox:
Same here, did some research and the only solution to get it to work is changing the config option
'browser.tabs.loadDivertedInBackground' to 'true'
launch background tab like this (or from py with os or subprocess module):
"C:\Program Files\Mozilla Firefox\firefox.exe" -new-tab "https://stackoverflow.com/"
See https://stackoverflow.com/a/2276679/2606766. But again I don't think this solves your problem, does it?
maybe you can try to stimulate the keyboard using pynput library,
then stimulating crtl + Tab to change to the new open website?
*edit: to open the previous tab, press crtl + shift + tab
import webbrowser, time
from pynput.keyboard import Key,Controller
keyboard = Controller()
webbrowser.open("https://www.youtube.com/")
time.sleep(3)
keyboard.press(Key.ctrl)
keyboard.press(Key.shift)
keyboard.press(Key.tab)
keyboard.release(Key.ctrl)
keyboard.release(Key.shift)
keyboard.release(Key.tab)
Are you familiar with CDP and Selenium?
Option A:
CDP Via Selenium Controlled browser:
from selenium import webdriver
driver = webdriver.Chrome('/path/bin/chromedriver')
driver.get("https://example.com/")
driver.execute_cdp_cmd(cmd="Target.createTarget",cmd_args={"url": 'https://stackoverflow.com/', "background": True})
"background": True is key
EDIT:
On linux the browser doesn't close, at least for me.
If it dies when the code dies, try the following:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
CHROME_DRIVER_PATH = '/bin/chromedriver'
chrome_options = Options()
chrome_options.add_experimental_option("excludeSwitches", ["enable-automation"])
chrome_options.add_experimental_option("detach", True)
driver = webdriver.Chrome(CHROME_DRIVER_PATH, chrome_options=chrome_options)
driver.get("https://example.com/")
driver.execute_cdp_cmd(cmd="Target.createTarget",cmd_args={"url": 'https://stackoverflow.com/', "background": True})
Option B:
Manually run chrome with a debug port (via cmd, subprocess.popen or anything else)
chrome.exe --remote-debugging-port=4455
and then either use a python CDP Client such as trio
or tell selenium to use your existing browser:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_experimental_option("debuggerAddress", "127.0.0.1:4455")
# Change chrome driver path accordingly
CHROME_DRIVER_PATH= r"C:\chromedriver.exe"
driver = webdriver.Chrome(CHROME_DRIVER_PATH, chrome_options=chrome_options)
driver.get("https://example.com/")
driver.execute_cdp_cmd(cmd="Target.createTarget",cmd_args={"url": 'https://stackoverflow.com/', "background": True})
Simpliest is to switch to -1 window_handles with chromedriver
from selenium import webdriver
driver = webdriver.Chrome('chrome/driver/path')
driver.switch_to.window(driver.window_handles[-1])

Error in python selenium 3 Edge web driver

I am a complete beginner to selenium and I wrote my first program just to connect to Google.
from selenium import webdriver
path = "C:\\Users\\Home\\Documents\\Python37-32\\Scripts\\Code\\msedgedriver.exe"
driver = webdriver.Edge(path)
driver.get("https://google.com")
print(driver.title)"
My web driver version is 88.0.705.50 (Official build) (64-bit)
I use selenium 3 and I am getting this error while running the code. Also it is opening "data:," for a few seconds then opening Google. Lastly the browser doesn't stay open.
Declare path on a separate line from the import statement
Use raw string in path or double escapes
Code:
from selenium import webdriver
path = r"C:\Users\Home\Documents\Python37-32\Scripts\Code\msedgedriver.exe"
driver = webdriver.Edge(path)
driver.get("https://google.com")
print(driver.title)
What error do you get? It's the default behavior that the browser opens with data:,, then it will direct to the website you want. The browser doesn't stay opened may because the error breaks it.
You can refer to the following steps to automate Edge in python selenium:
Make sure the WebDriver version is the same as the Edge version.
Install the MS Edge Selenium tools using command below:
pip install msedge-selenium-tools selenium==3.141
Sample code:
from msedge.selenium_tools import Edge, EdgeOptions
options = EdgeOptions()
options.use_chromium = True
driver = Edge(executable_path = r"C:\Users\Home\Documents\Python37-32\Scripts\Code\msedgedriver.exe", options = options)
driver.get("https://google.com")
print(driver.title)

Selenium Python - Webdriver

I am using selenium to crawl a javascript website, the issue is that, a Firefox browser opens up, but the call for the URL is not done. however, when I close the browser, it is then that call for URL is done and of course I get the missing driver exception. what do you think the issue comes from.
knowing that:
all programs are up-to-date
my solution works fine, in local, but when I try to deploy it on the server, I start having issues
Example: at my local machine, I run this script and everything goes smooth, however when I run it a server (Linux), only the browser opens up and no get URL is called
from selenium import webdriver
import time
geckodriver_path = r'.../geckodriver'
driver = webdriver.Firefox(executable_path= geckodriver_path)
time.sleep(3)
driver.get("http://www.stackoverflow.com")
I end up finding the solution :
from selenium import webdriver
import time
from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
geckodriver_path = r'/path_to/geckodriver'
binary = FirefoxBinary(r'/usr/bin/firefox')
capabilities = webdriver.DesiredCapabilities().FIREFOX
capabilities["marionette"] = False
driver = webdriver.Firefox(firefox_binary=binary,
executable_path= geckodriver_path,
capabilities=capabilities)
time.sleep(3)
driver.get("https://stackoverflow.com/")
time.sleep(6)
driver.close()
# solution from:
# https://github.com/SeleniumHQ/selenium/issues/3884
# https://stackoverflow.com/questions/25713824/setting-path-to-firefox-binary-on-windows-with-selenium-webdriver

Python selenium : How to close the tab that gets open automatically along with the tab that selenium opens

I installed chrome extension on chromedriver before I open the required url.
As the extension get installed, it opens a tab mentioning "Thank you for installing".
extension url:https://chrome.google.com/webstore/detail/buyhatke/jaehkpjddfdgiiefcnhahapilbejohhj?hl=en
I would like to close the tab opened by extension as it unnecessarily loads data.
code snippet:
from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
from bs4 import BeautifulSoup as soup
chrome_options = Options()
chrome_options.add_argument('load-
extension=C:\\Users\\SACHIN\\AppData\\Local\\Google\\Chrome\\User Data\\Default\\Extensions\\jaehkpjddfdgiiefcnhahapilbejohhj\\3.4.141_0')
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.implicitly_wait(30)
driver.get("https://paytm.com/shop/p/samsung-j3-pro-16-gb-black-MOBSAMSUNG-J3-PSTPL5914255C1B4E1C?src=grid&tracker=curated%7C%7Cmobile%20phones%7CCategory%20Grid%7C%2Fg%2Fmobile-accessories%2Fmobiles%2Fsmart-phones%7C66781%7C1%7C")
You can switch to tab as
window_before = driver.window_handles[0] // May be 1 in your case
driver.switch_to_window(window_before)
and close the driver.
Or send Alt + Tab keys and close the tab

Python Selenium open URL in same Firefox window

I am using Python Selenium to open a Firefox browser and go to a URL. The function I am using to do this is...
def openurl_function():
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
from selenium import webdriver
driver = webdriver.Firefox()
driver.get('http://www.example.com')
When I run the function it always opens a new instance of FireFox, is there a way to have it to just open using the same browser instance?
Currently if I run the function 10 times then I get 10 FireFox browsers open.
Just keep reusing the same driver. You are creating a new browser, every time you call
driver = webdriver.Firefox()
Also, because you never quit() on your driver, you will probably have all the browsers stay open as orphans because you deleted the handle to them when you created a new browser.

Categories

Resources