I learning python recent, but I have some error.
environment python3 , chrome , webdriver(chrome)
from selenium import webdriver
import time
import random
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
driver = webdriver.Chrome("./chromedriver.exe")
mobile_emulation = { "deviceName": 'Nexus 5' }
chrome_options = webdriver.ChromeOptions()
chrome_options.add_experimental_option("mobileEmulation", mobile_emulation)
driver = webdriver.Remote(command_executor='https:xxx.com',desired_capabilities = chrome_options.to_capabilities())
driver.get("https:/xxx.com")
num = random.randint(11111111 , 99999999)
red = driver.find_element_by_class_name("***")
red.click()
numBox = driver.find_element_by_name("***")
numBox.send_keys(int(num))
reader = driver.find_element_by_id("***")
reader.send_keys("***")
comment = driver.find_element_by_css_selector(" ***")
comment.click()
and result error is here
Traceback (most recent call last):
File "C:\python\pad\pad.py", line 16, in <module>
driver = webdriver.Remote(command_executor='https:xxx.com',desired_capabilities = chrome_options.to_capabilities())
File "C:\Users\***\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 156, in __init__
self.start_session(capabilities, browser_profile)
File "C:\Users\***\AppData\Local\Programs\Python\Python37-32\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 254, in start_session
self.session_id = response['sessionId']
TypeError: string indices must be integers
I think the error because number of this code includes Decimal. but I cant find such number .
please give me advise
This error message...
Traceback (most recent call last):
File "C:\python\pad\pad.py", line 16, in <module>
driver = webdriver.Remote(command_executor='https:xxx.com',desired_capabilities = chrome_options.to_capabilities())
.
TypeError: string indices must be integers
...implies that there was a TypeError while invoking webdriver.Remote() method.
As per your code trials as you are using webdriver.Remote() with the argument command_executor perhaps you were trying to execute your tests in Selenium Grid Configuration.
As per the documentation documentation:
command_executor : remote_connection.RemoteConnection object used to execute commands.
Example:
command_executor='http://127.0.0.1:4444/wd/hub'
The complete implementation:
driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities = chrome_options.to_capabilities())
Note: Here we have considered that the Selenium Grid Hub and Selenium Grid Node are configured, up and running successfully with default configuration on the localhost.
Solution (Python 3.6)
Your effective code block will be:
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("start-maximized")
chrome_options.add_argument('disable-infobars')
#driver = webdriver.Remote(command_executor='https:xxx.com', desired_capabilities = chrome_options.to_capabilities())
driver = webdriver.Remote(command_executor='http://127.0.0.1:4444/wd/hub', desired_capabilities = chrome_options.to_capabilities())
driver.get('https://www.google.co.in')
print("Page Title is : %s" %driver.title)
driver.quit()
Related
I have a weather station and take a screenshot of a webpage (windy.com) once an hour to integrate into my display which runs on a Pi 3
It was working perfectly until I had an SD card crash and had to rebuild it - I stupidly didn't have a backup of the SD card
I now have Pi OS Bullseye, Python 3.9.2 and Selenium 4.1.3
This is the old program that was working on PI OS Buster with Python 3.7 and Selenium 1.9ish
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from PIL import Image
import pygame
options = Options()
options.headless = True
options.add_argument('--user-agent="Mozilla/5.0 (Windows NT x.y; rv:10.0) Gecko/20100101 Firefox/10.0"')
driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver', options=options)
url = "https://embed.windy.com/embed2.html?lat=53.514&lon=-2.944&detailLat=53.393&detailLon=-2.134&width=530&height=490&zoom=4&level=surface&overlay=wind&product=ecmwf&menu=&message=true&marker=&calendar=now&pressure=true&type=map&location=coordinates&detail=&metricWind=mph&metricTemp=%C2%B0C&radarRange=-1"
driver.get(url)
driver.fullscreen_window()
driver.implicitly_wait(1)
driver.set_window_size(530,445)
driver.save_screenshot('weather.png')
basewidth = 530
img = Image.open('weather.png')
driver.quit()
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save('/home/pi/images/weather_icons/kia.bmp')}
It will not work with the new Pi Bullseye, Python3.9 and Selenium 2.4
I had so many errors and gradually got rid of them all but now I'm left with this error and I cannot figure out how to fix it
This is the error
Traceback (most recent call last):
File "/home/pi/map.py", line 6, in <module>
driver = webdriver.Chrome(service=s)
File "/home/pi/.local/lib/python3.9/site-packages/selenium/webdriver/chrome/webdriver.py", line 70, in __init__
super(WebDriver, self).__init__(DesiredCapabilities.CHROME['browserName'], "goog",
File "/home/pi/.local/lib/python3.9/site-packages/selenium/webdriver/chromium/webdriver.py", line 90, in __init__
self.service.start()
File "/home/pi/.local/lib/python3.9/site-packages/selenium/webdriver/common/service.py", line 98, in start
self.assert_process_still_running()
File "/home/pi/.local/lib/python3.9/site-packages/selenium/webdriver/common/service.py", line 110, in assert_process_still_running
raise WebDriverException(
selenium.common.exceptions.WebDriverException: Message: Service /usr/lib/chromium-browser/chromium-browser-v7 unexpectedly exited. Status code was: -5
This is the modified code I had to use to get this far
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from PIL import Image
path = ('/usr/lib/chromium-browser')
s = Service('/usr/lib/chromium-browser/chromium-browser-v7')
driver = webdriver.Chrome(service=s)
options = webdriver.ChromeOptions()
options.set_capability("goog:loggingPrefs", {'performance': 'ALL'})
url = "https://embed.windy.com/embed2.html?lat=53.514&lon=-2.944&detailLat=53.393&detailLon=-2.134&width=530&height=490&zoom=4&level=surface&overlay=wind&product=ecmwf&menu=&message=true&marker=&calendar=now&pressure=true&type=map&location=coordinates&detail=&metricWind=mph&metricTemp=%C2%B0C&radarRange=-1"
driver.get(url)
driver.fullscreen_window()
driver.implicitly_wait(1)
driver.set_window_size(530,445)
driver.save_screenshot('weather.png')
basewidth = 530
img = Image.open('weather.png')
driver.quit()
wpercent = (basewidth / float(img.size[0]))
hsize = int((float(img.size[1]) * float(wpercent)))
img = img.resize((basewidth, hsize), Image.ANTIALIAS)
img.save('/home/pi/images/weather_icons/kia.png')
My chromium-chromedriver is the latest version (98.0.4758) and my chromium browser is Version 98.0.4758.106
Can anyone tell me how to get this working without having to go back to the old versions of everything?
I am tried to use a headless google chrome to scrapy some website content in macOS Big Sur, this is my python 3 code:
from webbrowser import Chrome
from dolphin.common.commonlogger import CommonLogger
from selenium.webdriver import chrome
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys
class FetchMusic:
def __init__(self):
print("fetch...")
if __name__ == '__main__':
opts = Options()
opts.set_headless()
assert opts.headless # Operating in headless mode
browser = Chrome(executable_path=r"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
options=opts)
browser.implicitly_wait(3)
browser.get('https://ca.finance.yahoo.com/quote/AMZN/profile?p=AMZN')
results = browser.find_elements_by_xpath('//*[#id="quote-header-info"]/div[3]/div/div/span[1]')
for result in results:
print(result.text)
when I run this code, shows error:
Traceback (most recent call last):
File "/Users/dolphin/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/212.5457.59/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevd.py", line 1483, in _exec
pydev_imports.execfile(file, globals, locals) # execute the script
File "/Users/dolphin/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/212.5457.59/PyCharm.app/Contents/plugins/python/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "/Users/dolphin/source/reddwarf/backend/pydolphin/dolphin/biz/music/fetch.py", line 18, in <module>
opts.set_headless()
AttributeError: 'Options' object has no attribute 'set_headless'
python-BaseException
Process finished with exit code 1
what should I do to make it work?
Instead of
opts = Options()
opts.set_headless()
please use
options = ChromeOptions()
options.add_argument("--headless")
or
options = Options()
options.add_argument("--headless")
Imports :
from selenium.webdriver.chrome.options import Options as ChromeOptions
I am trying to monitor the network in the IE Webdriver, the following is my code:
import time
import psutil
import os
import json
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import trackin_config
caps = DesiredCapabilities.INTERNETEXPLORER
caps['loggingPrefs'] = {'performance': 'ALL'}
browser = webdriver.Ie(trackin_config.WEB_DRIVER, desired_capabilities=caps)
browser.get(trackin_config.MES_WEBSITE)
def process_browser_log_entry(entry):
response = json.loads(entry['message'])['message']
return response
browser_log = browser.get_log('performance')
events = [process_browser_log_entry(entry) for entry in browser_log]
events = [event for event in events if 'Network.response' in event['method']]
print(events)
However I am getting the following error:
File "c:/Adhil/Python/MES_BOT/trackin-bot.py", line 43, in <module>
browser_log = browser.get_log('performance')
File "C:\Users\Adh\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 1262, in get_log
return self.execute(Command.GET_LOG, {'type': log_type})['value']
File "C:\Users\Adh\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\webdriver.py", line 321, in execute
self.error_handler.check_response(response)
File "C:\Users\Adh\AppData\Local\Programs\Python\Python37\lib\site-packages\selenium\webdriver\remote\errorhandler.py", line 208, in check_response
raise exception_class(value)
selenium.common.exceptions.WebDriverException: Message:
Please advise, is there any package i need to install or configure?
errors = {}
for entry in context.browser.get_log('browser'):
errors.update(entry)
E
======================================================================
ERROR: test_LoginCorrect (__main__.LoginCorrect)
----------------------------------------------------------------------
Traceback (most recent call last):
File "demo.py", line 12, in test_LoginCorrect
driver= webdriver.Remote(desired_capabilities=DesiredCapabilities().FIREFOX,command_executor='http://0.0.0.0:4444')
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 156, in __init__
self.start_session(capabilities, browser_profile)
File "/usr/local/lib/python3.5/dist-packages/selenium/webdriver/remote/webdriver.py", line 248, in
start_session
self.session_id = response['sessionId']
TypeError: string indices must be integers
----------------------------------------------------------------------
Ran 1 test in 20.878s
//Formatting is not properly done
FAILED (errors=1)
My test case file :
import unittest
from selenium import webdriver
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
class LoginCorrect(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Remote(command_executor='http://0.0.0.0:4444/wd/hub', desired_capabilities=DesiredCapabilities.FIREFOX)
def test_LoginCorrect(self):
user ="shubh"
pwd= "sha123#56su"
driver= webdriver.Remote(desired_capabilities=DesiredCapabilities().FIREFOX,command_executor='http://0.0.0.0:4444')
driver.get("http://0.0.0.0:8000/login")
elem = driver.find_element_by_id("id_username")
elem.send_keys(user)
elem = driver.find_element_by_id("id_password")
elem.send_keys(pwd)
driver.find_element_by_class_name('btn-block').click()
def tearDown(self):
self.driver.quit()
if __name__ == '__main__':
unittest.main()
My machine has Linux 16.04LTS and selenium 3.3.0
Can somebody figure out this problem.
Ok, I am trying to set my browsers proxy file, I have everything configured correctly but not entirely sure why I keep getting this error.
Here is my code
from selenium import webdriver
import time
profile = webdriver.FirefoxProfile()
profile.set_preference('network.proxy.type', 1)
profile.set_preference('network.proxy.http', "173.255.117.227")
profile.set_preference('network.proxy.http_port', 7779)
profile.update_preferences()
driver = webdriver.Firefox(firefox_profile=profile)
driver.get('whatismyipaddress.com')
time.sleep(4)
driver.close()
This is the error I am getting -
========== RESTART: C:/Users/The Family/Desktop/FireFoxProxyBot.py ==========
Traceback (most recent call last):
File "C:/Users/The Family/Desktop/FireFoxProxyBot.py", line 4, in <module>
profile = webdriver.FirefoxProfile()
AttributeError: 'module' object has no attribute 'FirefoxProfile'
>>>