Home > Enterprise >  Can't use Selenium with for loop
Can't use Selenium with for loop

Time:07-22

I am trying to write a program with for loop and for that I need to declare Selenium webdriver before the loop. Each time I am trying to do it I get an error. Like the loop doesn't recognize driver.get part.

Here is the code:

from selenium import webdriver
import time
import csv



with open('smlxl.csv', 'r') as myFile:
    myReader = csv.reader(myFile)
    myList = list(myReader)

driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\chromedriver.exe')

for n in range(1,1000,4):

    barcode = (myList[n][24])
    url = ("https://www.google.com/search?q="   barcode)
    driver.get(url)
    print(n)

    n = (n 4)
    time.sleep(3)
    driver.close()

The error I get:

C:\Users\DELL\PycharmProjects\pythonProject3\erro.py:10: DeprecationWarning: executable_path has been deprecated, please pass in a Service object
  driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\chromedriver.exe')
1
Traceback (most recent call last):
  File "C:\Users\DELL\PycharmProjects\pythonProject3\erro.py", line 16, in <module>
    driver.get(url)
  File "C:\Users\DELL\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 447, in get
    self.execute(Command.GET, {'url': url})
  File "C:\Users\DELL\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 435, in execute
    self.error_handler.check_response(response)
  File "C:\Users\DELL\PycharmProjects\pythonProject3\venv\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 247, in check_response
    raise exception_class(message, screen, stacktrace)
selenium.common.exceptions.InvalidSessionIdException: Message: invalid session id
Stacktrace:
Backtrace:
    Ordinal0 [0x00326463 2188387]
    Ordinal0 [0x002BE461 1762401]
    Ordinal0 [0x001D3C40 801856]
    Ordinal0 [0x001F68BD 944317]
    Ordinal0 [0x001F7AD6 948950]
    GetHandleVerifier [0x005C71F2 2712546]
    GetHandleVerifier [0x005B886D 2652765]
    GetHandleVerifier [0x003B002A 520730]
    GetHandleVerifier [0x003AEE06 516086]
    Ordinal0 [0x002C468B 1787531]
    Ordinal0 [0x002C8E88 1805960]
    Ordinal0 [0x002C8F75 1806197]
    Ordinal0 [0x002D1DF1 1842673]
    BaseThreadInitThunk [0x7587FA29 25]
    RtlGetAppContainerNamedObjectPath [0x770D7A9E 286]
    RtlGetAppContainerNamedObjectPath [0x770D7A6E 238]


Process finished with exit code 1

Thank you for helping

CodePudding user response:

Had to place driver.close() outside the for loop.

CodePudding user response:

These error message...

selenium.common.exceptions.InvalidSessionIdException: Message: invalid session id

...implies that the previous session wasn't successfully killed/removed/eliminated.


Solution

You need to replace:

driver.close()

with:

driver.quit()

References

You can find a couple of relevant detailed discussions in:

  • Related