Aug 22, 2020 Sample code to get all links present on a webpage using Selenium WebDriver with Java. At times during automation, we are required to fetch all the links present on a webpage. Also, this is one of the most frequent requirements of web-scrapping. Primarily, it is for automating web applications for testing purposes, but is certainly not limited to just that. Boring web-based administration tasks can (and should!) also be automated as well. Some good guy has written a.net wrapper for selenium which can be used in VBA and VB.net and that is the wrapper we are going to use in this tutorial. Most popular libraries or frameworks that are used in Python for Web – Scrapping are BeautifulSoup, Scrappy & Selenium. In this article, we’ll talk about Web-scrapping using Selenium in Python. And the cherry on top we’ll see how can we gather images from the web that you can use to build train data for your deep learning project. Using Selenium v3.x opening a website in a New Tab through Python is much easier now. We have to induce an WebDriverWait for numberofwindowstobe(2) and then collect the window handles every time we open a new tab/window and finally iterate through the window handles and switchTo.window(newlyopened) as required.
Imagine what would you do if you could automate all the repetitive and boring activities you perform using internet, like checking every day the first results of Google for a given keyword, or download a bunch of files from different websites.
In this post you’ll learn to use Selenium with Python, a Web Scraping tool that simulates a user surfing the Internet. For example, you can use it to automatically look for Google queries and read the results, log in to your social accounts, simulate a user to test your web application, and anything you find in your daily live that it’s repetitive. The possibilities are infinite! 🙂
*All the code in this post has been tested with Python 2.7 and Python 3.4.
Install and use Selenium
Selenium is a python package that can be installed via pip. I recommend that you install it in a virtual environment (using virtualenv and virtualenvwrapper).
To install selenium, you just need to type:
In this post we are going to initialize a Firefox driver — you can install it by visiting their website. However, if you want to work with Chrome or IE, you can find more information here.
Once you have Selenium and Firefox installed, create a python file, selenium_script.py. We are going to initialize a browser using Selenium:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 | from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions asEC from selenium.common.exceptions import TimeoutException driver=webdriver.Firefox() returndriver driver.get('http://www.google.com') box=driver.wait.until(EC.presence_of_element_located( button=driver.wait.until(EC.element_to_be_clickable( box.send_keys(query) except TimeoutException: if__name__'__main__': lookup(driver,'Selenium') driver.quit() |
In the previous code:

- the function init_driver initializes a driver instance.
- creates the driver instance
- adds the WebDriverWait function as an attribute to the driver, so it can be accessed more easily. This function is used to make the driver wait a certain amount of time (here 5 seconds) for an event to occur.
- the function lookup takes two arguments: a driver instance and a query lookup (a string).
- it loads the Google search page
- it waits for the query box element to be located and for the button to be clickable. Note that we are using the WebDriverWait function to wait for these elements to appear.
- Both elements are located by name. Other options would be to locate them by ID,XPATH,TAG_NAME,CLASS_NAME,CSS_SELECTOR , etc (see table below). You can find more information here.
- Next, it sends the query into the box element and clicks the search button.
- If either the box or button are not located during the time established in the wait function (here, 5 seconds), the TimeoutException is raised.
- the next statement is a conditional that is true only when the script is run directly. This prevents the next statements to run when this file is imported.
- it initializes the driver and calls the lookup function to look for “Selenium”.
- it waits for 5 seconds to see the results and quits the driver
Finally, run your code with:
Did it work? If you got an ElementNotVisibleException , keep reading!
How to catch an ElementNotVisibleExcpetion
Google search has recently changed so that initially, Google shows this page:
Web Scraping Tutorial
and when you start writing your query, the search button moves into the upper part of the screen.
Well, actually it doesn’t move. The old button becomes invisible and the new one visible (and thus the exception when you click the old one: it’s not visible to click!).
We can update the lookup function in our code so that it catches this exception:
2 4 6 8 10 12 14 16 18 | from selenium.common.exceptions import ElementNotVisibleException def lookup(driver,query): try: box=driver.wait.until(EC.presence_of_element_located( button=driver.wait.until(EC.element_to_be_clickable( box.send_keys(query) button.click() button=driver.wait.until(EC.visibility_of_element_located( button.click() print('Box or Button not found in google.com') |
- the element that raised the exception, button.click() is inside a try statement.
- if the exception is raised, we look for the second button, using visibility_of_element_located to make sure the element is visible, and then click this button.
- if at any time, some element is not found within the 5 second period, the TimeoutException is raised and caught by the two end lines of code.
- Note that the initial button name is “btnK” and the new one is “btnG”.
Method list in Selenium
To sum up, I’ve created a table with the main methods used here.
Note: it’s not a python file — don’t try to run/import it 🙂
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 | from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait driver=webdriver.Firefox() # WAIT FOR ELEMENTS from selenium.webdriver.support import expected_conditions asEC element=driver.wait.until( EC.element_to_be_clickable( (By.NAME,'name') (By.LINK_TEXT,'link text') (By.TAG_NAME,'tag name') (By.CSS_SELECTOR,'css selector') ) # CATCH EXCEPTIONS TimeoutException |
That’s all! Hope it was useful! 🙂
Don’t forget to share it with your friends!
Beginner's guide to web scraping with python's selenium
In the first part of this series, we introduced ourselves to the concept of web scraping using two python libraries to achieve this task. Namely, requests and BeautifulSoup. The results were then stored in a JSON file. In this walkthrough, we'll tackle web scraping with a slightly different approach using the selenium python library. We'll then store the results in a CSV file using the pandas library.
The code used in this example is on github.
Why use selenium
Selenium is a framework which is designed to automate test for web applications.You can then write a python script to control the browser interactions automatically such as link clicks and form submissions. However, in addition to all this selenium comes in handy when we want to scrape data from javascript generated content from a webpage. That is when the data shows up after many ajax requests. Nonetheless, both BeautifulSoup and scrapy are perfectly capable of extracting data from a webpage. The choice of library boils down to how the data in that particular webpage is rendered.
Other problems one might encounter while web scraping is the possibility of your IP address being blacklisted. I partnered with scraper API, a startup specializing in strategies that'll ease the worry of your IP address from being blocked while web scraping. They utilize IP rotation so you can avoid detection. Boasting over 20 million IP addresses and unlimited bandwidth.
In addition to this, they provide CAPTCHA handling for you as well as enabling a headless browser so that you'll appear to be a real user and not get detected as a web scraper. For more on its usage, check out my post on web scraping with scrapy. Although you can use it with both BeautifulSoup and selenium.
If you want more info as well as an intro the scrapy library check out my post on the topic.
Using this scraper api link and the codelewis10, you'll get a 10% discount off your first purchase!
For additional resources to understand the selenium library and best practices, this article by towards datascience and accordbox.

Setting up
We'll be using two python libraries. selenium and pandas. To install them simply run pip install selenium pandas
In addition to this, you'll need a browser driver to simulate browser sessions.Since I am on chrome, we'll be using that for the walkthrough.
Driver downloads
- Chrome.
Getting started
For this example, we'll be extracting data from quotes to scrape which is specifically made to practise web scraping on.We'll then extract all the quotes and their authors and store them in a CSV file.
The code above is an import of the chrome driver and pandas libraries.We then make an instance of chrome by using driver = Chrome(webdriver)Note that the webdriver variable will point to the driver executable we downloaded previously for our browser of choice. If you happen to prefer firefox, import like so
Main script
Selenium Web Scraper
On close inspection of the sites URL, we'll notice that the pagination URL isHttp://quotes.toscrape.com/js/page/{{current_page_number}}/
where the last part is the current page number. Armed with this information, we can proceed to make a page variable to store the exact number of web pages to scrape data from. In this instance, we'll be extracting data from just 10 web pages in an iterative manner.
The driver.get(url) command makes an HTTP get request to our desired webpage.From here, it's important to know the exact number of items to extract from the webpage.From our previous walkthrough, we defined web scraping as
This is the process of extracting information from a webpage by taking advantage of patterns in the web page's underlying code.
We can use web scraping to gather unstructured data from the internet, process it and store it in a structured format.
On inspecting each quote element, we observe that each quote is enclosed within a div with the class name of quote. By running the directive driver.get_elements_by_class('quote')we get a list of all elements within the page exhibiting this pattern.
Final step
To begin extracting the information from the webpages, we'll take advantage of the aforementioned patterns in the web pages underlying code.
We'll start by iterating over the quote elements, this allows us to go over each quote and extract a specific record.From the picture above we notice that the quote is enclosed within a span of class text and the author within the small tag with a class name of author.
Finally, we store the quote_text and author names variables in a tuple which we proceed to append to the python list by the name total.
Using the pandas library, we'll initiate a dataframe to store all the records(total list) and specify the column names as quote and author.Finally, export the dataframe to a CSV file which we named quoted.csv in this case.
Don't forget to close the chrome driver using driver.close().
Adittional resources

1. finding elements
You'll notice that I used the find_elements_by_class method in this walkthrough. This is not the only way to find elements. This tutorial by Klaus explains in detail how to use other selectors.
What Is Web Scraping
2. Video
If you prefer to learn using videos this series by Lucid programming was very useful to me.https://www.youtube.com/watch?v=zjo9yFHoUl8
Selenium Web Scraping Python
3. Best practises while using selenium
4. Toptal's guide to modern web scraping with selenium
And with that, hopefully, you too can make a simple web scraper using selenium 😎.
If you enjoyed this post subscribe to my newsletter to get notified whenever I write new posts.
open to collaboration
I recently made a collaborations page on my website. Have an interesting project in mind or want to fill a part-time role?You can now book a session with me directly from my site.
Thanks.
