Scraping data from dropdown menus with Selenium in web development

When attempting Selenium web scraping, I encountered the following issues:

  1. Dropdown list did not change as expected
  2. Unable to scrape desired results
  3. Unsuccessful in resolving the problems

Here is a snippet of the code used:

'''
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.webdriver.support.select import Select
import time

driver=webdriver.Chrome(executable_path=r'C:\Program Files\Python39\chromedriver.exe')
driver.maximize_window()
driver.get("https://www.gastite.com/locator/?cats=109")

for i in range(1,3,1):
    state=driver.find_element(By.NAME, 'state')
    stateDD=Select(state)
    stateDD.select_by_index(i)
    driver.find_element(By.XPATH,'//*[@id="content"]/div[3]/form/input[2]')
    time.sleep(2)
    lists=driver.find_elements_by_css_selector("div.repcontent > a")
    
    for list in lists:
        try:
            company=list.find_element_by_class_name('namelink company_title').text
            address=list.find_element_by_class_name('address').text
            address1=list.find_element_by_class_name('address2').text
            tel=list.find_element_by_tag_name('span').text
            fax=list.find_element_by_tag_name('span').text
            web=list.get_attribute('href')
            print(company, address, address1, tel, fax, web)
        except Exception as e:
            print("Error: ", e)
    
'''

Answer №1

After choosing a specific state from the dropdown list as an example, the rest of your code attempts to extract data.

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait 
from selenium.webdriver.support import expected_conditions as EC

from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
from selenium.webdriver.support.select import Select
from bs4 import BeautifulSoup

driver = webdriver.Chrome(service=Service(ChromeDriverManager().install()))

url ='https://www.gastite.com/locator/?cats=109' 
driver.maximize_window()

Select(WebDriverWait(driver,20).until(EC.visibility_of_element_located((By.XPATH, "//select[@name='state']")))).select_by_value("AL")

soup = BeautifulSoup(driver.page_source,'lxml')
data=[]
for card in soup.select('#resultscontainer > ul > li > div.repcontent'):
    company = card.select_one('h3.company_title').text
    print(company)
    address = card.select_one('div.address').text
    address2 = card.select_one('div.address2').text
    phone = card.select('span').contents[0]
    fax = card.select('span').contents[1]

    data.append({
        'company':company,
        'address':address,
        'address2':address2,
        'phone':phone,
        'fax':fax
        })
        
print(data)

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

What kind of assistance does Selenium webdriver offer specifically for Firefox version 23?

Who can inform me about the Selenium webdriver compatibility with Firefox 23 or newer? ...

The amazing capabilities of Jmeter's WebDriver Sampler - Unleashing the Power of CSS Locator Wild

Recently, I've been utilizing Jmeter's built-in WebDriver Sampler with Selenium for web scraping. The Situation: In a particular scenario, it is crucial for me to only select the default date that is automatically chosen when opening a datepicke ...

What is the best way to execute a sequence of consecutive actions in a protractor test?

To achieve logging in, verifying, and logging out with multiple users, I decided to use a loop. I came across a helpful post that suggested forcing synchronous execution. You can find it here. Below are the scripts I implemented: it('instructor se ...

Finding the span element within a tooltip using Java

Having difficulty locating an element within span tags that is part of a tooltip appearing when the mouse hovers over it. Refer to the image here for better understanding: https://i.stack.imgur.com/b1qTg.jpg data from tooltip Whenever I hover my mouse on ...

The session does not support the 'css selector' Locator Strategy Exception error occurred when attempting to locate an instance of EditText using Appium in C#

Successfully opened my app using Appium in C#. Now, on the loginPage, I am trying to retrieve the EditText element in order to input the userName. I have attempted various methods, but they all seem to be causing issues. Here is a snippet of my code: pub ...

When using Selenium in Python, the get_attribute() method retrieves the specific data of an image instead of the URL

I'm currently working on a script to download images from Google Images. However, I've encountered an issue where attempting to extract the 'src' attribute of the image results in retrieving the image data rather than the link itself. T ...

Is there a way to display the data from a URL as selectable options in a dropdown menu?

I have a URL containing an arrayList of data. My task is to fetch the data from this URL and display it as options in a dropdown menu, allowing users to select the desired option. I am aware that this can be achieved using the Get method, but I am facing d ...

"Interacting with an unclickable element" issue encountered in Python Selenium

For the past year, I have been using the same scripts without any issues. However, starting yesterday, I encountered an error when clicking on links with images. The script locates the element by xpath and then attempts to click it. test_101_HomePage_link ...

Extracting elements from a dynamic website within the <script> tag using the libraries BeautifulSoup and Selenium

I am currently working on scraping a dynamic website using beautifulsoup and selenium. The specific attributes I need to filter and export into a CSV are all located within a <script> tag. My goal is to extract the information found in this script: ...

Quick fixes in Eclipse (Java) do not offer the import option

class automation_example { public static void main(String[] args) { new ChromeDriver(); } } When trying to create a new instance of ChromeDriver, the import driver option does not appear when hovering over it. The JAVA jar file has been a ...

Navigating through Excel download prompts with Selenium WebDriver

What is the best way to deal with an Excel download popup when using Selenium WebDriver? ...

Attempting to retrieve information from a website, but unfortunately not having any luck

from urllib.request import urlopen as uReq from requests import get from bs4 import BeautifulSoup as soup import tablib my_url = 'https://tradingeconomics.com/india/indicators' uClient2 = uReq(my_url) page_html = uClient2.read() uClient ...

Which type of quote - single or double - is used to enclose the value in an Xpath while searching for a web element in

Is there a difference between using single quotes ' or double quotes " in Xpath for the value? I need to extract a web element <div class="has-error ng-scope ng-hide" ng-show="element['ServerValidationFailed']">Sorry, that isn't ...

How can I enable editing for specific cells in Angular ag-grid?

How can I make certain cells in a column editable in angular ag-grid? I have a grid with a column named "status" which is a dropdown field and should only be editable for specific initial values. The dropdown options for the Status column are A, B, C. When ...

Is there a way to simulate pressing arrow keys randomly using Selenium in Python?

My current project involves creating a program that can play the game 2048 by randomly choosing arrow keys. I attempted the following code snippet: moves = [htmlElem.send_keys(Keys.UP),htmlElem.send_keys(Keys.RIGHT),htmlElem.send_keys(Keys.DOWN),htmlEle ...

Pop-up warning - endless search cycle

As a novice, my question might be a bit strange :) I want to test the Main Menu of the website "https://tvn24.pl/" I am searching for elements, adding them to a list, and then iterating through each one to open every discovered page - everything is worki ...

Having trouble selecting a dynamically changing div element in Selenium with Java using a click action

Every time I navigate to www.reddit.com and enter a query in the Search field, then press enter to go to the first valid link within a subreddit, sorting options are presented. By default, it is set to BEST but I wish to change it to TOP. My test class cod ...

What is the process for selecting an element within an iframe?

When attempting to interact with the iframe (recaptcha) and the button with the headphone icon on the site https://www.google.com/recaptcha/api2/demo, I am encountering difficulties. How can I successfully click on these elements? What mistake am I making? ...

Using selenium webdriver to scan barcodes with a webcam on web applications

Currently, I am working on automating the process of scanning barcodes within a web application. The steps involved in this scenario are as follows: 1. Launching the web application 2. Opening the webcam function within the web application 3. Scanning the ...

Solving the issue of TypeError: 'module' object is not callable error with Selenium and ChromeDriver

Experimenting with code: from selenium import webdriver from selenium.webdriver.chrome.options import Options as Chromeoptions chrome_options = Chromeoptions() chrome_options.add_extension('Metamask.crx') driver = webdriver.chrome("./chrom ...