To address the CAPTCHA issue using async_tls_client, you'll need to integrate asynchronous HTTP requests with a headless browser to handle the CAPTCHA. async_tls_client is a library that provides asynchronous TLS connections, which can be useful for making secure HTTP requests.
However, handling CAPTCHAs typically requires a more sophisticated approach, such as using a CAPTCHA-solving service or a headless browser with a CAPTCHA-solving extension. For this example, I'll show you how to use async_tls_client to make the initial request and then use selenium to handle the CAPTCHA and scrape the data.
Prerequisites
Python 3.8+
Install required libraries:
bash
pip install async_tls_client selenium pandas
Download ChromeDriver and ensure it's in your system's PATH.
Code
python
import asyncio
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
import async_tls_client
# Set up the webdriver
def setup_webdriver():
options = webdriver.ChromeOptions()
options.add_argument("--headless") # Optional: Run in headless mode
return webdriver.Chrome(options=options)
# Perform the search and scrape the results
async def scrape_kings_county_surrogates_court(driver):
url = "https://websurrogates.nycourts.gov/File/FileSearch"
session = async_tls_client.Session()
# Make the initial request to get the page
async with session.get(url) as response:
page_content = await response.text()
# Use Selenium to handle the CAPTCHA and interact with the page
driver.get(url)
# Select "Kings County Surrogate's Court" from the Court dropdown
court_select = Select(WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "ddlCourt"))
))
court_select.select_by_visible_text("Kings County Surrogate's Court")
# Select "ADMINISTRATION PETITION" from the File Proceeding dropdown
proceeding_select = Select(driver.find_element(By.ID, "ddlProceedingType"))
proceeding_select.select_by_visible_text("ADMINISTRATION PETITION")
# Enter the File Date range
file_date_from = driver.find_element(By.ID, "txtFileDateFrom")
file_date_from.send_keys("04/01/2025")
file_date_to = driver.find_element(By.ID, "txtFileDateTo")
file_date_to.send_keys("04/30/2025")
# Submit the search form
search_button = driver.find_element(By.ID, "btnSearch")
search_button.click()
try:
# Wait for the results page to load
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "NameResultsTable"))
)
# Extract the table data
table = driver.find_element(By.ID, "NameResultsTable")
table_html = table.get_attribute("outerHTML")
df = pd.read_html(table_html)[0]
# Rename columns to match the required output
df = df.rename(columns={"File #": "File Number", "File Date": "File Date"})
return df[["File Number", "File Date"]]
except TimeoutException:
print("Timed out waiting for the results page to load.")
return None
# Main function
async def main():
driver = setup_webdriver()
try:
results_df = await scrape_kings_county_surrogates_court(driver)
if results_df is not None:
print(results_df)
finally:
driver.quit()
if __name__ == "__main__":
asyncio.run(main())
Explanation
Initial Request with async_tls_client:
The script uses async_tls_client to make an initial request to the website. This can help in handling TLS connections asynchronously.
Selenium for CAPTCHA Handling:
After making the initial request, the script uses Selenium to handle the CAPTCHA and interact with the webpage. This is necessary because CAPTCHAs are designed to prevent automated access.
Scraping the Data:
Once the CAPTCHA is solved (manually or using a CAPTCHA-solving service), the script proceeds to select the required options, submit the form, and scrape the data from the results table.
Note
CAPTCHA Handling: This script assumes that the CAPTCHA will be solved manually. For automated CAPTCHA solving, you might need to integrate a CAPTCHA-solving service like 2Captcha or Anti-Captcha.
Ethical Considerations: Ensure you have permission to scrape the website and comply with its terms of service. Overloading the website with requests can be considered unethical and may lead to your IP being blocked.
This approach combines the strengths of async_tls_client for asynchronous requests and Selenium for handling CAPTCHAs and interacting with the webpage.
The website you mentioned, https://iapps.courts.state.ny.us/webcivil/FCASCalendarSearch, likely requires JavaScript-based operations to interact with the page, including form submissions and handling dynamic content. This means that a simple HTTP request won't be sufficient to scrape the data, and you'll need to simulate a browser session to handle these interactions.
For such tasks, selenium is a good choice because it can automate a web browser, handle JavaScript, and interact with web elements just like a human user would. Below is an example of how you can use selenium to scrape data from this website.
Prerequisites
Python 3.8+
Install required libraries:
bash
pip install selenium pandas
Download ChromeDriver and ensure it's in your system's PATH.
import pandas as pd
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select, WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
# Set up the webdriver
def setup_webdriver():
options = webdriver.ChromeOptions()
options.add_argument("--headless") # Optional: Run in headless mode
return webdriver.Chrome(options=options)
# Perform the search and scrape the results
def scrape_calendar_search(driver):
url = "https://iapps.courts.state.ny.us/webcivil/FCASCalendarSearch"
driver.get(url)
# Wait for the page to load and select the required elements
try:
# Select the court from the dropdown
court_select = Select(WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "courtName"))
))
court_select.select_by_visible_text("Kings County Civil Court")
# Enter the date range
date_from = driver.find_element(By.ID, "dateFrom")
date_from.send_keys("04/01/2025")
date_to = driver.find_element(By.ID, "dateTo")
date_to.send_keys("04/30/2025")
# Submit the search form
search_button = driver.find_element(By.ID, "searchButton")
search_button.click()
# Wait for the results to load
WebDriverWait(driver, 10).until(
EC.presence_of_element_located((By.ID, "resultsTable"))
)
# Extract the table data
table = driver.find_element(By.ID, "resultsTable")
table_html = table.get_attribute("outerHTML")
df = pd.read_html(table_html)[0]
# Rename columns to match the required output
df = df.rename(columns={"File Number": "File Number", "File Date": "File Date"})
return df[["File Number", "File Date"]]
except TimeoutException:
print("Timed out waiting for the results page to load.")
return None
# Main function
def main():
driver = setup_webdriver()
try:
results_df = scrape_calendar_search(driver)
if results_df is not None:
print(results_df)
finally:
driver.quit()
if __name__ == "__main__":
main()
Explanation
Setup WebDriver:
The script sets up a webdriver instance using ChromeDriver.
Navigate to the URL:
The script navigates to the specified URL.
Select Court and Date Range:
The script selects the court from the dropdown and enters the date range.
Submit the Form:
The script submits the search form and waits for the results to load.
Extract Table Data:
The script extracts the table data using pandas and renames the columns to match the required output.
Handle Exceptions:
The script handles timeout exceptions to ensure it doesn't hang if the results page takes too long to load.
Note
CAPTCHA Handling: If the website has a CAPTCHA, you might need to solve it manually or use a CAPTCHA-solving service.
Ethical Considerations: Ensure you have permission to scrape the website and comply with its terms of service. Overloading the website with requests can be considered unethical and may lead to your IP being blocked.
This approach uses selenium to handle JavaScript-based operations and interact with the webpage, making it suitable for scraping data from websites that require dynamic content loading and form submissions.