Scroll down google maps webpage using selenium python - selenium

I am trying to collect data on a google map webpage, however i can't find a way to scroll down the page to get all the data.
I'm using python 3 and Selenium package,
thank you in advance,

Try this code it works for me
SCROLL_PAUSE_TIME = 5
last_height = driver.execute_script("return document.body.scrollHeight")
number = 0
while True:
number = number+1
Scroll down to bottom
ele = driver.find_element_by_xpath('//*[#id="QA0Szd"]/div/div/div[1]/div[2]/div/div[1]/div/div/div[2]')
driver.execute_script('arguments[0].scrollBy(0, 5000);', ele)
Wait to load page
time.sleep(SCROLL_PAUSE_TIME)
Calculate new scroll height and compare with last scroll height
ele = driver.find_element_by_xpath('//*[#id="QA0Szd"]/div/div/div[1]/div[2]/div/div[1]/div/div/div[2]')
new_height = driver.execute_script("return arguments[0].scrollHeight", ele)
if new_height == last_height:
break
last_height = new_height

You can try to locate the element and use browserelement.execute_script("arguments[0].scrollIntoView(true);",option)
For example:
driver.get("https://www.google.com/maps/place/Bengaluru,+Karnataka/#12.95396,77.4908522,11z/data=!4m5!3m4!1s0x3bae1670c9b44e6d:0xf8dfc3e8517e4fe0!8m2!3d12.9715987!4d77.5945627")
option = driver.find_element_by_xpath("//div[#class='hNLpDc-HiaYvf-DWDkFd-HiaYvf-haAclf']")
driver.execute_script("arguments[0].scrollIntoView(true);",option)

To scroll down with selenium:
driver.execute_script('window.scrollTo(0, document.body.scrollHeight);')
and smooth way
driver.execute_script('window.scrollTo({ top: document.body.scrollHeight, behavior: "smooth" });')

Related

How can we find only the WebElements present on the viewport with using selenium python find_elements method?

I want to automate the task of scrolling through a web page and clicking on the buttons. But, when trying to find web elements with driver.find_elements() getting a list of all web elements which are not present on the viewport so clicking on them results in error "MoveTargetOutOfBounds"
def like(self):
likeButtonXpath = '//div[#aria-label="Like"]'
try:
a = ActionChains(self.browser)
likeWebElements = self.browser.find_elements(
By.XPATH, likeButtonXpath)
for element in likeWebElements:
try:
a.move_to_element(element).perform()
sleep(3)
element.click()
except:
print("error while clicking button")
except Exception as e:
print(e)
def scrollLike(self):
last_height = self.browser.execute_script(
"return document.body.scrollHeight")
cnt = self.maxScroll
curHeight = last_height
while cnt >= 0:
self.like()
self.browser.execute_script("window.scrollBy(0,1000)", "")
sleep(30)
new_height = self.browser.execute_script(
"return document.body.scrollHeight")
if new_height == last_height:
break
last_height = new_height
cnt -= 1
Is not possible to tell driver.find_elements to limit its search on the elements in the viewport. A possible workaround would be to compute the coordinates of the element and then scroll to them, but this is usually an hard task and almost impossible to get precise coordinates.
With javascript and scrollIntoView we can easily bring the desired element within the viewport.
driver.execute_script('arguments[0].scrollIntoView();', element)
By adding block: "center" the scroll will be executed in such a way that element is at the center of the viewport. By adding behavior: "smooth" the scroll will be smooth.
driver.execute_script('arguments[0].scrollIntoView({block: "center", behavior: "smooth"});', element)

Check if it's possible to scroll down with RSelenium

I'm using RSelenium to automatically scroll down a social media website and save posts. Sometimes I get to the bottom of the webpage and no more posts can be loaded as no more data is available. I just want to be able to check if this is the case so I can stop trying to scroll.
How can I tell if it's possible to continue scrolling in RSelenium? The code below illustrates what I'm trying to do - I think I just need help with the "if" statement.
FYI there's a solution for doing this in Python here (essentially checking if page height changes between iterations), but I can't figure out how to implement it (or any another solution) in R.
# Open webpage
library(RSelenium)
rD = rsDriver(browser = "firefox")
remDr = rD[["client"]]
url = "https://stocktwits.com/symbol/NZDCHF"
remDr$navigate(url)
# Keep scrolling down page, loading new content each time.
ptm = proc.time()
repeat {
remDr$executeScript("window.scrollTo(0,document.body.scrollHeight);")
Sys.sleep(3) #delay by 3sec to give chance to load.
# Here's where i need help
if([INSERT CONDITION TO CHECK IF SCROLL DOWN IS POSSIBLE]) {
break
}
}
Stumbled across a way to do this in Python here and modified it to work in R. Below is a now-working update of the original code I posted above.
# Open webpage
library(RSelenium)
rD = rsDriver(browser = "firefox")
remDr = rD[["client"]]
url = "https://stocktwits.com/symbol/NZDCHF"
remDr$navigate(url)
# Keep scrolling down page, loading new content each time.
last_height = 0 #
repeat {
remDr$executeScript("window.scrollTo(0,document.body.scrollHeight);")
Sys.sleep(3) #delay by 3sec to give chance to load.
# Updated if statement which breaks if we can't scroll further
new_height = remDr$executeScript("return document.body.scrollHeight")
if(unlist(last_height) == unlist(new_height)) {
break
} else {
last_height = new_height
}
}

SVG Selenium click do not work

I want to simulate a simple mouse click and drag within an svg element.
I managed to get the coordinates of my starting and ending point, both absolute (window coordinates) and relative to the encapsulating svg element.
Here is the code I am using to simulate the mouse:
Actions builder = new Actions(driver);
builder.moveToElement(area, xStart, yStart);
builder.clickAndHold();
builder.moveToElement(area, xStop, yStop);
builder.release();
Action setFilter = builder.build();
setFilter.perform();
Where area is a WebElement representing my svg and the coordinates are relative to that element. Note that:
area.getLocation(); // returns null
This made me wonder whether the webdriver is able to find that element at all. So I tried with absolute coordinates:
Actions builder = new Actions(driver);
builder.moveByOffset(chart.getLocation().x + xStart, chart.getLocation().y + yStart);
builder.clickAndHold();
builder.moveByOffset(xStop - xStart, yStop - yStart);
builder.release();
Action setFilter = builder.build();
setFilter.perform();
where chart is the div surrounding the svg element (note that the offset between the div position and the svg position is only 10 pixels and is not significant). That didn't work either and I also tried by relative position to the div but still no luck.
What am I doing wrong here?
I got a hack for it to work but it requires the webpage to be opened on the foreground. If you're doing anything else at the same time it may break the test and I cannot say if it would work if ran remotely.
Here's what it looks like:
Robot robert = new Robot();
robert.mouseMove(xStart, yStart);
// full click once to get focus on the window
robert.mousePress(MouseEvent.BUTTON1_MASK);
robert.mouseRelease(MouseEvent.BUTTON1_MASK);
// then set the filter
robert.mousePress(MouseEvent.BUTTON1_MASK);
robert.mouseMove(xStop, yStop);
robert.mouseRelease(MouseEvent.BUTTON1_MASK);

Need to scroll from clicked div to top of browser window. Not to top of document, using Isotope Jquery

Please take a look at my jsFiddle here
I am using jQuery Isotope plugin and I am having troubles using their itemPositionDataEnabled to be able to scroll from my clicked item to the top of whats currently visible in the browsers window.
With itemPositionDataEnabled I should be able to extract the x and y position of what ever item I'm requesting. However mine does nothing at all....
var $this = $(this),
scrollTop = $(window).scrollTop(),
itemPosition = $this.data('isotope-item-position'),
itemPositionY = $this.itemPosition.y,
distance = (itemPositionY - scrollTop);
$('html, body').stop().animate({
scrollTop: distance
}, 1000);
You have a plain and simple error in these two lines:
itemPosition = $this.data('isotope-item-position'),
itemPositionY = $this.itemPosition.y;
The second line should be:
itemPositionY = itemPosition.y;
Not sure if you're all the way there since it only seems to work on the way you want on the first click.
http://jsfiddle.net/EA8tM/90/

Clicking at coordinates without identifying element

As part of my Selenium test for a login function, I would like to click a button by identifying its coordinates and instructing Selenium to click at those coordinates. This would be done without identifying the element itself (via id, xpath, etc).
I understand there are other more efficient ways to run a click command, but I'm looking to specifically use this approach to best match the user experience. Thanks.
There is a way to do this. Using the ActionChains API you can move the mouse over a containing element, adjust by some offset (relative to the middle of that element) to put the "cursor" over the desired button (or other element), and then click at that location. Here's how to do it using webdriver in Python:
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
browser = webdriver.Chrome()
elem = browser.find_element_by_selector(".some > selector")
ac = ActionChains(browser)
ac.move_to_element(elem).move_by_offset(x_offset, y_offset).click().perform()
Y'all are much to quick to dismiss the question. There are a number of reasons one might to need to click at a specific location, rather than on an element. In my case I have an SVG bar chart with an overlay element that catches all the clicks. I want to simulate a click over one of the bars, but since the overlay is there Selenium can't click on the element itself. This technique would also be valuable for imagemaps.
In C# API you use actions
var element = driver.FindElement(By...);
new Actions(driver).moveToElement(element).moveByOffset(dx, dy).click().perform();
Although it is best to just use simple Id, CSS, Xpath selectors when possible. But the functionality is there when needed (i.e. clicking elements in certain geographic places for functionality).
I first used the JavaScript code, it worked amazingly until a website did not click.
So I've found this solution:
First, import ActionChains for Python & active it:
from selenium.webdriver.common.action_chains import ActionChains
actions = ActionChains(driver)
To click on a specific point in your sessions use this:
actions.move_by_offset(X coordinates, Y coordinates).click().perform()
NOTE: The code above will only work if the mouse has not been touched, to reset the mouse coordinates use this:
actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0))
In Full:
actions.move_to_element_with_offset(driver.find_element_by_tag_name('body'), 0,0)
actions.move_by_offset(X coordinates, Y coordinates).click().perform()
This can be done using Actions class in java
Use following code -
new Actions(driver).moveByOffset(x coordinate, y coordinate).click().build().perform();
Note: Selenium 3 doesn't support Actions class for geckodriver
Also, note that x and y co-ordinates are relative values from current mouse position. Assuming mouse co-ordinates are at (0,0) to start with, if you want to use absolute values, you can perform the below action immediately after you clicked on it using the above code.
new Actions(driver).moveByOffset(-x coordinate, -y coordinate).perform();
If using a commercial add-on to Selenium is an option for you, this is possible: Suppose your button is at coordinates x=123, y=456. Then you can use Helium to click on the element at these coordinates as follows:
from helium.api import *
# Tell Helium about your WebDriver instance:
set_driver(driver)
click(Point(123, 456))
(I am one of Helium's authors.)
This worked for me in Java for clicking on coordinates irrespective on any elements.
Actions actions = new Actions(driver);
actions.moveToElement(driver.findElement(By.tagName("body")), 0, 0);
actions.moveByOffset(xCoordinate, yCoordinate).click().build().perform();
Second line of code will reset your cursor to the top left corner of the browser view and last line will click on the x,y coordinates provided as parameter.
In Selenium Java, you can try it using Javascript:
WebDriver driver = new ChromeDriver();
if (driver instanceof JavascriptExecutor) {
((JavascriptExecutor) driver).executeScript("el = document.elementFromPoint(x-cordinate, y-cordinate); el.click();");
}
Action chains can be a little finicky. You could also achieve this by executing javascript.
self.driver.execute_script('el = document.elementFromPoint(440, 120); el.click();')
I used the Actions Class like many listed above, but what I found helpful was if I need find a relative position from the element I used Firefox Add-On Measurit to get the relative coordinates.
For example:
IWebDriver driver = new FirefoxDriver();
driver.Url = #"https://scm.commerceinterface.com/accounts/login/?next=/remittance_center/";
var target = driver.FindElement(By.Id("loginAsEU"));
Actions builder = new Actions(driver);
builder.MoveToElement(target , -375 , -436).Click().Build().Perform();
I got the -375, -436 from clicking on an element and then dragging backwards until I reached the point I needed to click. The coordinates that MeasureIT said I just subtracted. In my example above, the only element I had on the page that was clickable was the "loginAsEu" link. So I started from there.
If all other methods mentioned on this page failed and you are using python, I suggest you use the mouse module to do it in a more native way instead. The code would be as simple as
import mouse
mouse.move("547", "508")
mouse.click(button='left')
You can also use the keyboard module to simulate keyboard actions
import keyboard
keyboard.write('The quick brown fox jumps over the lazy dog.')
To find the coordinate of the mouse, you can use the follow JavaScript Code.
document.onclick=function(event) {
var x = event.screenX ;
var y = event.screenY;
console.log(x, y)
}
If you don't like screenX, you can use pageX or clientX. More on here
P.S. I come across a website that prevents programmatic interactions with JavaScript/DOM/Selenium. This is probably a robot prevention mechanism. However, there is no way for them to ban OS actions.
WebElement button = driver.findElement(By.xpath("//button[#type='submit']"));
int height = button.getSize().getHeight();
int width = button.getSize().getWidth();
Actions act = new Actions(driver);
act.moveToElement(button).moveByOffset((width/2)+2,(height/2)+2).click();
import pyautogui
from selenium import webdriver
driver = webdriver.Chrome(chrome_options=options)
driver.maximize_window() #maximize the browser window
driver.implicitly_wait(30)
driver.get(url)
height=driver.get_window_size()['height']
#get browser navigation panel height
browser_navigation_panel_height = driver.execute_script('return window.outerHeight - window.innerHeight;')
act_y=y%height
scroll_Y=y/height
#scroll down page until y_off is visible
try:
driver.execute_script("window.scrollTo(0, "+str(scroll_Y*height)+")")
except Exception as e:
print "Exception"
#pyautogui used to generate click by passing x,y coordinates
pyautogui.FAILSAFE=False
pyautogui.moveTo(x,act_y+browser_navigation_panel_height)
pyautogui.click(x,act_y+browser_navigation_panel_height,clicks=1,interval=0.0,button="left")
This is worked for me. Hope, It will work for you guys :)...
I used AutoIt to do it.
using AutoIt;
AutoItX.MouseClick("LEFT",150,150,1,0);//1: click once, 0: Move instantaneous
Pro:
simple
regardless of mouse movement
Con:
since coordinate is screen-based, there should be some caution if the app scales.
the drive won't know when the app finish with clicking consequence actions. There should be a waiting period.
To add to this because I was struggling with this for a while. These are the steps I took:
Find the coordinates you need to click. Use the code below in your console and it will display and alert of the coordinates you need.
document.onclick = function(e)
{
var x = e.pageX;
var y = e.pageY;
alert("User clicked at position (" + x + "," + y + ")")
};
Make sure the element is actually visible on the screen and click it using Actionchains
WebDriverWait(DRIVER GOES HERE, 10).until(EC.element_to_be_clickable(YOUR ELEMENT LOCATOR GOES HERE))
actions = ActionChains(DRIVER GOES HERE)
actions.move_by_offset(X, Y).click().perform()
Selenium::WebDriver has PointerActions module which includes a number of actions you can chain and/or trigger without specifying the element, eg. move_to_location or move_by. See detailed specs here. As you can see, you can only use actual coordinates. I am sure this interface is implemented in other languages / libraries accordingly.
My short reply may echo some other comments here, but I just wanted to provide a link for reference.
You could use the html tag as the element and then use the coordinates you want, in this example below I am using Javascript. But I am able to click on the top left of the screen.
async function clickOnTopLeft() {
const html = driver.wait(
until.elementLocated(By.xpath('/html')),
10000)
const { width, height } = await html.getRect()
const offSetX = - Math.floor(width / 2)
const offsetY = - Math.floor(height / 2)
await driver.actions().move(
{ origin: html, x: offSetX, y: offsetY })
.click().perform()
}
If you can see the source code of page, its always the best option to refer to the button by its id or NAME attribute. For example you have button "Login" looking like this:
<input type="submit" name="login" id="login" />
In that case is best way to do
selenium.click(id="login");
Just out of the curiosity - isnt that HTTP basic authentification? In that case maybe look at this:
http://code.google.com/p/selenium/issues/detail?id=34
Selenium won't let you do this.