Having problems initiating a remote session with WebDriver - encountering a TypeError: string indices should be integers

As one of my initial attempts at writing a Python script, I am working on running a test case on localhost hosted on an IIS server in a local environment. To achieve this, I have made the following adjustments:

  1. Changed Firefox Settings to 'No proxy'
  2. Configured and redirected the URL in IIS so that '127.0.0.1' directs to the website. This means entering 127.0.0.1 in the browser redirects to the local website in IIS

I encountered a geoLocation alert prompt that requires manual interaction. To automate this process, I took the following steps:

  1. Created a new Firefox profile
  2. Set its preferences to allow alerts for geoLocation services
  3. Set socks proxy to 127.0.0.1
  4. Set Desired Capabilities

The provided code snippet showcases how this was implemented:

class CheckGeoLocationsDropDown():

        def test_check_geo_locations_dropdown(self):

            try:

                selenium_profile = webdriver.FirefoxProfile()

                # Setting up necessary preferences
                selenium_profile.set_preference("network.proxy.socks", '127.0.0.1')
                selenium_profile.set_preference("network.proxy.socks_port", 80)
                selenium_profile.update_preferences()

                baseUrl = 'http://127.0.0.1:80'

                capabilities = DesiredCapabilities.FIREFOX.copy()
                capabilities['platform'] ="WINDOWS"
                capabilities['version'] = "7"
                capabilities['nativeEvents'] = True
                capabilities['unexpectedAlertBehaviour'] = 'Accept'
                
                driver = webdriver.Remote(desired_capabilities=capabilities,
                                          command_executor='http://127.0.0.1:80',
                                          browser_profile=selenium_profile)

                driver.maximize_window()

                driver.get(baseUrl)
                driver.implicitly_wait(5)
                driver.refresh()
                driver.close()

                item = '*'
                print(item * 40 + 'Geo Locations Dropdown selected successfully' + item * 40)

        except NoSuchElementException:
            print("Couldn't Run Script")

ff = CheckGeoLocationsDropDown()
ff.test_check_geo_locations_dropdown()

Error message link: https://i.stack.imgur.com/dldJd.png

Despite reviewing Python documents, I wasn't able to identify the issue. Any guidance would be highly appreciated.

UPDATE 1/29/2018:

To handle geolocation permission request alerts, I included the preference

selenium_profile.set_preference('media.navigator.permission.‌​disabled', True)

I also added two lines as follows:

capabilities['nativeEvents'] = True
capabilities['unexpectedAlertBehaviour'] = 'Accept'

However, the error persists.

REFERENCES USED:

Answer №1

The information provided lacks details for specific recommendations regarding the error stack trace, making it challenging to provide a precise answer. However, I was able to successfully reproduce the issue.

Upon reviewing the current implementation of

selenium.webdriver.remote.webdriver
, we find that it is defined as:

class selenium.webdriver.remote.webdriver.WebDriver(command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities=None, browser_profile=None, proxy=None, keep_alive=False, file_detector=None, options=None)

Exploring the source code of the Public Method set_preference(self, key, value), we see various preferences that can be configured in the profile using this method:

self.default_preferences[key] = value

List of Preferences

  • set_preference("webdriver_firefox_port", self._port)
  • set_preference("webdriver_accept_untrusted_certs", value)
  • set_preference("webdriver_assume_untrusted_issuer", value)
  • set_preference("webdriver_enable_native_events", value)
  • set_preference("network.proxy.type", proxy.proxy_type['ff_value'])
  • set_preference("network.proxy.no_proxies_on", proxy.no_proxy)
  • set_preference("network.proxy.autoconfig_url", proxy.proxy_autoconfig_url)
  • set_preference("network.proxy.%s" % key, host_details[0])
  • set_preference("network.proxy.%s_port" % key, int(host_details2))

No matching preference was found for the preference you mentioned:

set_preference('media.navigator.permission.disabled', True)

This could be the reason for the error you encountered.


Update

Regarding your question update on detecting geolocation permission and being able to allow/block geolocation sharing, you can include the following line of code:

opt.add_experimental_option("prefs", { \
    "profile.default_content_setting_values.geolocation": 1, 
  })

For further details, refer to a detailed discussion here.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Processing JSON data in django view

I am looking to integrate the api that I have created using django_rest_framework into my API. I need to utilize the JSON data produced in both my views and templates. The JSON data structure looks like this - [ { "url": "http://127.0.0.1:8000/app/clubs/ ...

Python SocketTypeError: troubleshooting socket issues

import socket, sys, string if len(sys.argv) !=4: print ("Please provide the server, port, and channel as arguments: ./ninjabot.py <server> <port> <channel>") sys.exit(1) irc = sys.argv[1] port = int(sys.argv[2]) chan = sys.argv ...

Adding multiple images to email HTML with Python made easy

Looking for a solution to embed 15 .jpg images from a single folder into the body of an email without them shrinking when stacked vertically. My initial approach was to create one long image with all photos but it reduced in size as more pictures were adde ...

Optimizing the process of inputting the date, month, and year into separate dropdown menus

I'm new to automation and facing an issue with efficiently inputting date, month, and year from three different dropdowns with unique xpaths. I want to streamline this process without using the select class for each dropdown. Here is the sample code ...

`` `eliminate quotation marks in a json document with the help of python

On PowerBI, the 'dataset' dataframe is automatically generated. Below are the results of my dataset.head(10).to_clipboard(sep=',', index=False) coordinates,status "[143.4865219,-34.7560602]",not started "[143.4865241,-34.7561332]",not ...

Appium is reporting a console error stating, "The specified search parameters were unable to locate an element on the page."

Having difficulty finding the element in my mobile app. ` public class Ovex { private static AndroidDriver driver; public static void main(String[] args) throws MalformedURLException, InterruptedException { DesiredCapabilities capabilities = n ...

Struggling to manage the cookies section

I'm encountering an issue with the cookies page on a website when I try to launch it. Specifically, I need assistance in clicking the "Allow Cookies" button within that frame. Can someone please provide guidance? driver = new FirefoxDriver(); driver. ...

Converting Beautiful Soup output into a DataFrame using Python

I am currently facing a challenge with web scraping. I am trying to extract data from a betting website, scrape it, and then store it in a dataframe. Here is the code snippet I am using: import numpy as np import pandas as pd from urllib.parse import urlj ...

Utilizing Python's regular expressions for parsing and manipulating Wikipedia text

I am attempting to convert wikitext into plain text using Python regular expressions substitution. There are two specific formatting rules for wiki links: [[Name of page]] [[Name of page | Text to display]] (http://en.wikipedia.org/wiki/Wikipedia:Cheat ...

I am having trouble with the find_elements_by_class_name function in Selenium using Python

I am searching for web elements that share the same class name in order to capture screenshots of elements for my application. I have opted to utilize Selenium with Python for this task. url = "https://www.pexels.com/search/happy/" driver = webdr ...

Leveraging PowerShell to run a script on a remote machine that triggers a batch file

Having trouble running a batch file on a remote server to execute an automated Selenium test On a remote server, there is a batch file named mybatch.bat that triggers a Selenium test. Below is the code snippet in a Powershell script on the same server: $ ...

Retrieving a JavaScript variable from a Python Selenium request

Currently, I am utilizing Python in conjunction with Selenium to monitor changes on our pbx system. A specific value that I require is being retrieved through a JavaScript call and unfortunately, it is not directly written into the HTML code. This has made ...

How to combine data frames using multiple intervals

Looking for a solution similar to this question: Fastest way to merge pandas dataframe on ranges However, I have multiple ranges to take into account during the merging process. I possess a dataframe labeled A: ip_address server_port 0 13 ...

Tips for fixing the Python error message "can only concatenate str (not "float") to str" when trying to return a string

I have been working on a project to determine the percentage of landmass that a country occupies compared to the total landmass of the world. My function takes in two arguments, one as a string and the other as a float, and returns a string with the calcul ...

Utilize Python to extract targeted JSON keys and transform them into CSV format

My code currently converts all data in a JSON file into a CSV, but I need it to only extract specific nested data. Here's the desired process: Load JSON file [done] Extract certain nested data in the JSON file [wip] Convert to CSV [done] Existing Co ...

Seamlessly Loading Comments onto the Page without Any Need for Refresh

I am new to JavaScript and I am trying to understand how to add comments to posts dynamically without needing to refresh the page. So far, I have been successful in implementing a Like button using JS by following online tutorials. However, I need some gui ...

Tips for capturing network traffic with Selenium WebDriver and BrowserMob Proxy in Python

For my project, I am working on capturing network traffic using Selenium Webdriver with Python. In order to achieve this, I need to utilize a proxy such as BrowserMobProxy. Everything works smoothly when using webdriver.Chrome: from browsermobproxy impor ...

What is the method to interact with an expand & collapse button in selenium using Java?

I'm trying to click on the expand button in order to view the menu items. @Then("^click on set up$") public void click_on_set_up() throws Throwable { driver.findElement(By.cssSelector("btn-header pull-right")).click(); } I ...

What is the best way to extract data from multiple pages with varying xpaths in Selenium?

Seeking assistance with scraping a sequence of pages similar to the following: . The structure of the URLs is straightforward -- increment the number after "precinctreport" to navigate to subsequent pages. Specifically, I am interested in extracting only ...

Remove any empty spaces within a string that appears on the same line as a specific string

I'm a beginner in the world of Python and this marks my first attempt at coding. While I have come across similar issues while researching solutions, as a newcomer, I am struggling to adapt them to my specific needs. Therefore, I've taken the lib ...