0

it is possible to use two python scripts on the same chromedriver browser if the first python script opens the page with chromedriver and the second one python script search on google on the page opened by the chromedriver in the first python script.

I wrote the following code but I don't know how to do what I said above.

First Python Script:

import time
import second_script.py
from selenium import webdriver
driver = webdriver.Chrome("driver87/chromedriver.exe")
driver.get('http://www.google.com/')
time.sleep(5)
execfile('second_script.py')

And the second one should contain:

import time
driver.switch_to.frame(0)
driver.find_element_by_id("introAgreeButton").click()
time.sleep(1)
search_box = driver.find_element_by_name('q')
search_box.send_keys('text searched on google')
search_box.submit()
time.sleep(20)
driver.quit()

I hope someone can help me, and I hope you understand what I want to do. Thanks!

stxdb
  • 13
  • 2

2 Answers2

2

Personally, I wouldn't recommend merging the scripts, but if you strongly want 2 scripts, then you need to add a function into the second script and call it from the first. For example, this is what the first script needs to look like:

import time
import second_script
from selenium import webdriver
driver = webdriver.Chrome()
driver.get('http://www.google.com/')
time.sleep(5)
second_script.main(driver)

Here, we import the script and call the function main() which we will define in the second script.

Now, this is what the second script should look like:

import time

def main(driver):
    driver.switch_to.frame(0)
    driver.find_element_by_id("introAgreeButton").click()
    time.sleep(1)
    search_box = driver.find_element_by_name('q')
    search_box.send_keys('text searched on google')
    search_box.submit()
    time.sleep(20)
    driver.quit()

What we have done over here is create a function called main() and put all of the code into that function. We then added an argument called driver to avoid any errors and to merge the 2 drivers together.

Dharman
  • 30,962
  • 25
  • 85
  • 135
The Pilot Dude
  • 2,091
  • 2
  • 6
  • 24
0

In your second script:

import time


def search(driver):
    driver.switch_to.frame(0)
    driver.find_element_by_id("introAgreeButton").click()
    time.sleep(1)
    search_box = driver.find_element_by_name('q')
    search_box.send_keys('text searched on google')
    search_box.submit()
    time.sleep(20)
    
    driver.quit()

In your first script:

import time
import second_script

from selenium import webdriver

driver = webdriver.Chrome("driver87/chromedriver.exe")
driver.get('http://www.google.com/')
time.sleep(5)
second_script.search(driver)

This should work, fine however as others have said this is quite a bad design.

GAP2002
  • 870
  • 4
  • 20