Quantcast
Channel: Active questions tagged selenium - Stack Overflow
Viewing all 97797 articles
Browse latest View live

Send CTRL+Shift+I in Selenium Python using Action Chains

$
0
0

How to send CTRL + Shift + I in selenium using ActionChains. I followed many examples such as:

Web Driver API | 7.2. Action Chains

For Selenium with Python, how can i get it to press CTRL, SHIFT, i?

But, those don't work for me. I don't know, what I missed. Maybe because I using a different script. Please help me to send CTRL + SHift + I.

I re-use existing Selenium browser. I was trying to use Action Chains and select element. But, both are not working.

def Execute(executor_url, session_id, data):    options = Options()    options.page_load_strategy = 'normal'    options.add_argument("--disable-infobars")    options.add_argument("--enable-file-cookies")    capabilities = options.to_capabilities()    driver = webdriver.Remote(command_executor=executor_url, desired_capabilities=capabilities)    driver.close()    driver.session_id = session_id    link="https://google.com"    driver.execute_script("window.open('{}');".format(link))    ## Trying to use ActionChains    ActionChains(driver).send_keys(Keys.CONTROL, Keys.SHIFT, 'i').perform()    ## Trying to use element    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL, Keys.SHIFT, 'i')    sys.exit()

Thanks.


Is it possible in Python to play sound/music from website without open the browser?

$
0
0

I found some solution with Selenium, but Selenium open the browser to play the selected music, so it's not the perfect way for me.

Is it possible to play music from website without open the browser?

How do you start a Selenium in Firefox or Chrome?

$
0
0

How to set up a Selenium in Google or Chrome?

I have tried both to no success.

It will be on raspberry pi model b v1.1

Second iterative of find_elements_by_xpath gives error in selenium python

$
0
0

I'm trying to find all the my subject in my dashboard of my college website.I'm using selenium to do it.The site is a little slow so first I wait

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='multiline']")))

then I find all the elements with

course = driver.find_elements_by_xpath("//span[@class='multiline']")

after that in a for loop I try to traverse it the 0th place of the "course" works fine and I'm able to click it and go to webpage but when the loop runs for the secon d time that is for the 1st place in "course" it gives me error selenium.common.exceptions.StaleElementReferenceException: Message: stale element reference: element is not attached to the page document

So I tried adding a lit bit wait time to using 2 method it still gives me error

driver.implicitly_wait(20)WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='multiline']")))

the loop

for i in course[1::]:#driver.implicitly_wait(20)#WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//span[@class='multiline']")))print(i)i.click()driver.implicitly_wait(2)driver.back()

a snippet of the website

enter image description here

Thanks in advance

How to download images from facebook with python and selenium

$
0
0

i'm approaching python with selenium in these days, and i would like retrieve all photos from an album in facebook. I've started to work with "xpath" system and it works, but there's a problem:

  • When you open-up an album on facebook, it only loads some images. You can not even catch the images with full path, "they" are not loaded untill you scroll down and trigger the "load function" for load more images.

That's a big problem, because you can not know how many photo are in the album, and you can only load the first 20/25 photos :/

i've tried some trick (like simulate arrow down, scroll down...) but i didn't found a soluction. Does anyone have it ?

That's My code:

# Include Libs import os, time, keyboardfrom selenium import webdriverfrom selenium.common.exceptions import NoSuchElementExceptionimport urllib.requestdef clear(): os.system('cls') #Clear Console # Maindriver = webdriver.Chrome()driver.get('*Link to a facebook album that you want download*')print("Log in...")time.sleep(10) # prevent lockfor x in range(1, 622): #i've manually count that there are 621 photos!  mystring = "/html/body/div[1]/div/div[1]/div[1]/div[3]/div/div/div[1]/div[1]/div[1]/div/div[2]/div/div/div/div[1]/div/div[{0:d}]/a/div/img".format(x)  img = driver.find_element_by_xpath(mystring)  src = img.get_attribute('src')  urllib.request.urlretrieve(src, "{0:d}.png".format(x))  time.sleep(1)

getting attribute gives error after one loop in selenium [duplicate]

$
0
0

i want to get source from a job listing site but when i click on a job link and get description than come back get_attribute() method gets broken.i am new to this stuff so i need some help on this.

my code:

all_jobs = driver.find_elements_by_class_name("index-middle")for job in all_jobs: result_html = job.get_attribute("innerHTML") soup = BeautifulSoup(result_html, "html.parser")  showmore=WebDriverWait(driver, 15).until(EC.presence_of_element_located((By.CLASS_NAME,'job')))  showmore.click() try:     description = soup.find("a",class_="desc").text except:     description = "None" driver.execute_script("window.history.go(-1)")

i want to repeat this action in for loop but when it gets a one job description it gives error.

error:

  Traceback (most recent call last):    File "joblist.py", line 46, in <module>    result_html = job.get_attribute("innerHTML")selenium.common.exceptions.StaleElementReferenceException: Message: stale elementreference: element is not attached to the page document

what should i do ?

How to fix error: selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable [duplicate]

$
0
0

I am writing a code that asks the user for a type of music and redirects them to a playlist in YouTube which is related to what the user wrote. While trying to click on the "Filter" button on YouTube to access the diferent playlist I encountered the following error:selenium.common.exceptions.ElementNotInteractableException: Message: element not interactable.

Is there any way of making that button interactable?

While searchinig for a way to solve it, some of the solutions recommended using an explicit wait, but the timer reaches it's limits:

raise TimeoutException(message, screen, stacktrace)selenium.common.exceptions.TimeoutException: Message: 

Here is my code:

from selenium import webdriverfrom selenium.webdriver.common.keys import Keysfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EClink= "https://www.youtube.com/"PATH= "C:\Program Files (x86)\chromedriver.exe"driver= webdriver.Chrome(PATH)driver.get(link)print("\n")print(driver.title)genre= input("What kind of music do you want?: ")print("Looking in YouTube's playlists ("+ genre+")...")search_bar= driver.find_element_by_name("search_query")search_bar.send_keys(genre+" playlist")print(driver.current_url)search_button= driver.find_element_by_id("search-icon-legacy")search_button.click()filter_pl = WebDriverWait(driver, 120).until( #Without the explicit wait this line would be: filter_pl= driver.find_element_by_id("button")EC.element_to_be_clickable((By.ID, "button")) #Without the explicit wait this line wouldn't existfilter_pl.click()

Selenium 3.141.59 with clj-webdriver and chromedriver fail on method not found from Guava [duplicate]

$
0
0

Using clj-webdriver with seleniumhq and chromedriver(86) and when test starts I still get this issue.

Exception in thread "main" java.lang.NoSuchMethodError: com.google.common.collect.ImmutableList.toImmutableList()Ljava/util/stream/Collector;at org.openqa.selenium.chrome.ChromeOptions.asMap(ChromeOptions.java:292)at org.openqa.selenium.MutableCapabilities.merge(MutableCapabilities.java:73)at org.openqa.selenium.remote.DesiredCapabilities.merge(DesiredCapabilities.java:107)at org.openqa.selenium.remote.DesiredCapabilities.merge(DesiredCapabilities.java:33)at org.openqa.selenium.MutableCapabilities.setCapability(MutableCapabilities.java:96)...

It says it cannot find method from com.google.guava but I can see that guava-25.0-jre.jar is fetched in project dependencies but it is somehow ignored.

Also weird thing is that from stacktrace ChromeOptions.asMap() is refering to line 292 in ChromeOptions.java but when I check that class there's no such line so it looks like it is refering to different version of selenium-chrome-driver but then again in deps there's 3.141.59 version.

Checked all the dependencies and cannot seem to find place where old guava or old selenium-chrome-driver should live.

Dependencies looks like:

:dependencies [[org.seleniumhq.selenium/selenium-java "3.141.59"][org.clojure/clojure "1.10.1"][clj-webdriver "0.7.2" :exclusions [     [org.seleniumhq.selenium/selenium-server]     [org.seleniumhq.selenium/selenium-java]     [org.seleniumhq.selenium/selenium-remote-driver]     [com.codeborne/phantomjsdriver]]][org.seleniumhq.selenium/htmlunit-driver "2.44.0"][com.google.guava/guava "25.0-jre"][clj-http "3.10.3"][cheshire "5.10.0"][clj-time "0.15.2"]]

I spent on this like whole day and running out of ideas.Any ideas why this error appears?


How to clone a Selenium.Builder object (for Selenium WebDriver)?

$
0
0

Selenium (WebDriver) has in all of its bindings (here I will use JavaScript, but the question is equally valid for the others) a Builder class that is used to create a WebDriver. For example:

import {Builder} from 'selenium-webdriver';const builder = new Builder()  .forBrowser('firefox')  .setProxy({'proxyType': 'manual', 'httpProxy': '127.0.0.1'});const driver = await builder.build(); // returns a WebDriver

Now I want to clone a Builder instance. What I can do for this is to clone the capabilities only:

const clone = new Builder();clone.withCapabilities(builder.getCapabilities());

This changes some of the Builder attributes, e.g. the browser name and the proxy, but not all.

Additionally, I can set some of the missing values, e.g.

clone.setFirefoxOptions(build.getFirefoxOptions());

But again many attributes are missing; e.g., there is no build.getEdgeOptions (while there is a clone.setEdgeOptions), and there is no clone.setAlertBehavior (while there is a build.getAlertBehavior).

So, is there any way to fully clone a Builder?

After loggin sucsessfuly instapy do not do tasks given with session (exit with no replay just close connection)

$
0
0

python "instagrambot Final.py" --username techno_booster --passwordpass! --like_by tags --batch_file tags.txt -a 50 InstaPy Version:0.6.12 .. .. .. .. .. .. .. .. ._. Workspace in use: "C:/Users/jjsol/InstaPy"OOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOOO INFO[2020-11-13 12:42:15] [techno_booster] Session started!oooooooooooooooooooooooooooooooooooooooooooooooooooooo INFO[2020-11-13 12:42:15] [techno_booster] -- Connection Checklist [1/2](Internet Connection Status) INFO [2020-11-13 12:42:15][techno_booster] - Internet Connection Status: ok INFO [2020-11-1312:42:15] [techno_booster] - Current IP is "162.199.218.100" and it'sfrom "United States/US" INFO [2020-11-13 12:42:16] [techno_booster] --Connection Checklist [2/2] (Hide Selenium Extension) INFO [2020-11-1312:42:16] [techno_booster] - window.navigator.webdriver response: NoneINFO [2020-11-13 12:42:16] [techno_booster] - Hide Selenium Extension:ok....................................................................INFO [2020-11-13 12:42:32] [techno_booster] Logged in successfully!''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''INFO [2020-11-13 12:42:32] [techno_booster] Saving account progress...INFO [2020-11-13 12:42:48] [techno_booster] Tag [1/3] INFO [2020-11-1312:42:48] [techno_booster] --> b'techno' INFO [2020-11-13 12:42:57][techno_booster] desired amount: 59 | top posts [disabled]: 9 |possible posts: 0 INFO [2020-11-13 12:43:04] [techno_booster] Tag:b'techno' INFO [2020-11-13 12:43:04] [techno_booster] Tag [2/3] INFO[2020-11-13 12:43:04] [techno_booster] --> b'rave' INFO [2020-11-1312:43:13] [techno_booster] desired amount: 59 | top posts [disabled]:9 | possible posts: 0 INFO [2020-11-13 12:43:19] [techno_booster] Tag:b'rave' INFO [2020-11-13 12:43:19] [techno_booster] Tag [3/3] INFO[2020-11-13 12:43:19] [techno_booster] --> b'technodj' INFO[2020-11-13 12:43:26] [techno_booster] desired amount: 59 | top posts[disabled]: 9 | possible posts: 0 INFO [2020-11-13 12:43:35][techno_booster] Tag: b'technodj' INFO [2020-11-13 12:43:35][techno_booster] Liked: 0 INFO [2020-11-13 12:43:35] [techno_booster]Already Liked: 0 INFO [2020-11-13 12:43:35] [techno_booster]Commented: 0 INFO [2020-11-13 12:43:35] [techno_booster] Followed: 0INFO [2020-11-13 12:43:35] [techno_booster] Inappropriate: 0 INFO[2020-11-13 12:43:35] [techno_booster] Not valid users: 0 I just usebasic config one task per run and its stop when its need to perform anaction

this is the configs.

if(args.proxy and args.username and args.password):    session = InstaPy(username=args.username, password=args.password, proxy_address=args.proxy, proxy_port=args.port, headless_browser=True)else:    session = InstaPy(username=args.username, password=args.password,  headless_browser=True)session.login()##Quota Supervisior dhourly and day limitssession.set_quota_supervisor(enabled=True, sleep_after=["likes", "comments_d", "follows", "unfollows", "server_calls_h"], sleepyhead=True, stochastic_flow=True, notify_me=True,                              peak_likes_hourly=45,                              peak_likes_daily=1000,                               peak_comments_hourly=21,                               peak_comments_daily=182,                                peak_follows_hourly=48,                                peak_follows_daily=None,                                 peak_unfollows_hourly=35,                                 peak_unfollows_daily=402,                                  peak_server_calls_hourly=None,                                  peak_server_calls_daily=4700)## Like by tags  or location## Usage## python3 instagrambot.py --username user --password pass --proxy 80.80.80.80 -p 443 --like_by tags|location --batch_file file.txt -a 100 for 100 likes if batch_file have 100 locations## This is used to perform likes on your own feeds## interact True visits the author's profile page of a certain post and likes a given number of his pictures, then returns to feed else Falseif args.like_by == 'tags' or args.like_by == 'location':    with open(args.batch_file, 'r') as file:        data = [line.strip() for line in file]        if(args.like_by == 'location'):            session.like_by_locations(data, amount=args.amount)        elif(args.like_by == 'tags'):            session.like_by_tags(data, amount=args.amount)

This is geckodriver.log

###!!! [Child][MessageChannel::SendAndWait] Error: Channel error:cannot send/recv

1605289329583 geckodriver INFO Listening on 127.0.0.1:563741605289332638 mozrunner::runner INFO Running command: "C:\ProgramFiles\Mozilla Firefox\firefox.exe" "--marionette" "-foreground""-no-remote" "-profile""C:\Users\jjsol\AppData\Local\Temp\rust_mozprofileHTslWF" Can't findsymbol 'eglSwapBuffersWithDamageEXT'. JavaScript error:resource://gre/modules/XULStore.jsm, line 66: Error: Can't findprofile directory. console.warn: SearchSettings: "get: No settingsfile exists, new profile?" (new Error("", "(unknown module)"))1605289335031 Marionette INFO Listening on port 56382 1605289335306Marionette WARN TLS certificate errors will be ignored for thissession JavaScript error: resource://gre/modules/URIFixup.jsm, line271: NS_ERROR_FAILURE: Should pass a non-null uri 1605289430722Marionette INFO Stopped listening on port 56382

###!!! [Child][RunMessage] Error: Channel closing: too late to send/recv, messages will be lost

###!!! [Child][MessageChannel::SendAndWait] Error: Channel error: cannot send/recv

Selenium Chrome Webdriver not working in headless mode with profile

$
0
0

So, this is the code I'm having troubles with:

def scrap():        options = webdriver.ChromeOptions();        options.add_argument('headless');        options.add_argument('--profile-directory=Profile 1')        options.add_argument("--user-data-dir=C:/Users/omarl/AppData/Local/Google/Chrome/User Data/")        options.add_argument("--remote-debugging-port=45447")        options.add_argument("--disable-gpu")         browser = webdriver.Chrome(executable_path=r"C:\Users\omarl\OneDrive\Escritorio\chromedriver.exe", options=options)        scrapURL = "https://es.wallapop.com/search?distance=30000&keywords=leggins&latitude=41.38804&longitude=2.17001&filters_source=quick_filters"        browser.get(scrapURL)        #...

And the error:

WebDriverException: unknown error: unable to discover open pages

I don't have any instances of chrome when I execute the script, and when I'm using it without the headless option it works fine. Any idea why this is happening? Please, note that I'm using the --remote-debuggin-port provided in similar questions.

I'm using ChromeDriver 86.0.4240.22

How I can insert a text into a textfield with Selenium?

$
0
0

I am working on a project with Python and Selenium.In the image you can see the code of the input field in which I try to insert my text.

<input data-v-382b0a6e="" id="expiration" name="expiration" type="text" required="required" data-test="expiration-input" autocomplete="billing cc-exp" dir="auto" class="form-textbox form-textbox-text form-textbox-entered" style="" aria-invalid="true">

Web elements

My first approach was to use the .send_keys(variable) function. The issue there is that the variable month will be inserted in the year. I tried to clear the input field and click into it before, but it didn't help.

WebDriverWait(driver, 30).until(    EC.presence_of_element_located(        (By.XPATH, "//*[@data-test='expiration-input']"))).send_keys(expMonth) 

The following image shows the error.

Issue

I also tried to use a Javascript executor to insert a value into this input field, but it has no value attribute and it won't use this attribute.

I have clue what I can do here anymore.Has someone a hint for me how I can insert my text into this field?

Selenium Python - get elements and click on each

$
0
0

i want to store elements in a list and click on each of them one by one. But I have to reach the < u > - Element, because .click() only works, when I click on that < u > - xpath and not on the class-Element.

<a href="javascript:doQuery(...);" class="report"><u>Test1</u><a href="javascript:doQuery(...);" class="report"><u>Test2</u><a href="javascript:doQuery(...);" class="report"><u>Test3</u>

Any tips? Thanks.

Webscraping Click Button Selenium

$
0
0

I am trying to webscrape indeed.com to search for jobs using python, with selenium and beautifulsoup. I want to click next page but cant seem to figure out how to do this. Looked at many threads but it is unclear to me which element I am supposed to perform on. Here is the web page html and the code marked with grey comes up when I inspect the next button.

enter image description here

Also just to mention I tried first to follow what happens to the url when mousedown is executed. After reading the addppurlparam function and adding the strings in the function and using that url I just get thrown back to page one.

Here is my code for the class with selenium meant to click on the button:

   from selenium import webdriverfrom selenium.webdriver import ActionChainsdriver = webdriver.Chrome("C:/Users/alleballe/Downloads/chromedriver.exe")driver.get("https://se.indeed.com/Internship-jobb")print(driver.title)#assert "Python" in driver.titleelem = driver.find_element_by_class_name("pagination-list")elem = elem.find_element_by_xpath("//li/a[@aria-label='Nästa']")print(elem)assert "No results found." not in driver.page_sourceassert elemaction = ActionChains(driver).click(elem)action.perform()print(elem)driver.close()

Get Flask-Testing server URL in setUpClass

$
0
0

I am writing unittest for my Flask web app using Selenium using Flask-Testing's LiveServer.

When running my test, I want to have one browser for all the tests instead of opening a new browser instance for each test, so I am using unittest's setUpClass.

class TestApp(LiveServerTestCase, unittest.TestCase):    def create_app(self):        app = create_app()        app.config['TESTING'] = True        app.config.update(LIVESERVER_PORT=9898)        return app    @classmethod    def setUpClass(cls):        cls.chrome_browser = webdriver.Chrome()        cls.chrome_browser.get(cls.get_server_url())    def test_main_page(self):        self.assertEqual(1, 1)

When running my test, I am getting the following:

TypeError: get_server_url() missing 1 required positional argument: 'self'

How can I set up the browser in setUpClass?


Using Selenium, how can I tell VBA to repeat this portion of the macro for all rows in a column

$
0
0

I'm not sure what should I use to instruct the macro to repeat this part of the process for all rows in column A Starting with A1.

obj.FindElementById("txtProgramCode").SendKeys (ThisWorkbook.Sheets("Sheet2").Range("A1").Value)obj.FindElementById("btnQuery").Clickobj.FindElementByClass("close").Clickobj.SwitchToAlert.Acceptobj.SwitchToAlert.Acceptobj.FindElementById("txtProgramCode").Clear

Data comes out as one text ,I want to divide the data into course name, description, so on

$
0
0
'element=driver.find_element_by_xpath('//td[@class="block_content"]')    with open('asin_data.csv', 'a', newline='') as f:        f.write(element.text+"\n")    print(element.text)    driver.back()'

I need to divide the data of element into the csv file

Unable to use pywinauto to connect to "Open" dialog window in Google Chrome when selenium to upload image in Instagram

$
0
0

Using Seleniumwebdriver, I was able to automate the login and navigate to profile and change the view to Mobile view. Then used the code below to click on the "+" icon.The Open Dialog window opens but pywinauto was not able to connect it. There was No error message also, once i close the browser, then i get the error message saying unable to find the Mentioned window

browser.find_element_by_xpath("""//*[@id="react-root"]/section/nav[2]/div/div/div[2]/div/div/div[3]""").click()app=Application().connect(title=u'Open',class_name='#32770')app.Open.print_control_identifiers()

Any help would be much appreciated.

Thanks

Python proxy authentication through Selenium chromedriver

$
0
0

We tried for a few days to setup Proxy Authentication with selenium chromedriver in Python.We couldn't set ip up because Chrome throws a pop-up for authentication. Problem is that selenium can't switch to that window and so, can't type. The only solution that worked for us was using pyautogui which is a bad solution for us because we want to use the headless function.

Here are all the methods we tried:

driver.switch_to_window()
driver.switch_to_active_element()
driver.switch_to_alert()
ActionChains(driver).send_keys("test").perform()
driver.switch_to_alert()
options = webdriver.ChromeOptions()options.add_argument('--proxy-server=http://user:pass@3.223.68.195:31112')
driver.get("https://user:pass@google.com")
proxy = {'address': '3.209.253.119:31112','username': 'user','password': 'pass'}capabilities = dict(DesiredCapabilities.CHROME)capabilities['proxy'] = {'proxyType': 'MANUAL','httpProxy': proxy['address'],'ftpProxy': proxy['address'],'sslProxy': proxy['address'],'noProxy': '','class': "org.openqa.selenium.Proxy",'autodetect': False}capabilities['proxy']['socksUsername'] = proxy['username']capabilities['proxy']['socksPassword'] = proxy['password']driver = webdriver.Chrome(executable_path="chromedriver.exe", desired_capabilities=capabilities)driver.get("http://google.com")

Any help would be really appreciated :)

SOLVED: How to Send CTRL+Shift+I in Selenium Python

$
0
0

How to send CTRL + Shift + I in selenium using ActionChains. I followed many examples such as:

Web Driver API | 7.2. Action Chains

For Selenium with Python, how can i get it to press CTRL, SHIFT, i?

But, those don't work for me. I don't know, what I missed. Maybe because I using a different script. Please help me to send CTRL + Shift + I.

I re-use existing Selenium browser. I was trying to use Action Chains and select an element. But, both are not working without any error logs.

def secondProccess(executor_url, session_id, data):    options = Options()    options.page_load_strategy = 'normal'    options.add_argument("--disable-infobars")    options.add_argument("--enable-file-cookies")    capabilities = options.to_capabilities()    driver = webdriver.Remote(command_executor=executor_url, desired_capabilities=capabilities)    driver.close()    driver.session_id = session_id    link="https://google.com"    driver.execute_script("window.open('{}');".format(link))    action = webdriver.ActionChains(driver)    ## Trying to use ActionChains    action.send_keys(Keys.CONTROL, Keys.SHIFT, 'i').perform()    ## Trying to use ActionChain key down    action.key_down(Keys.CONTROL).key_down(Keys.SHIFT).send_keys("i").perform()    ## Trying to use element    driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL, Keys.SHIFT, 'i')    sys.exit()

Thanks.

Viewing all 97797 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>