import time
import os
import csv
from playwright.sync_api import sync_playwright
def solve_captcha(captcha_image_path):
"""
Simulate a CAPTCHA solving process manually as
current implementation assumes manual entry for simplicity.
"""
print("Manual CAPTCHA solving required. Please solve the CAPTCHA:")
solved_captcha = input("Enter the CAPTCHA value displayed in the image: ")
return solved_captcha
def scrape_patent_data(patent_number):
"""
Scrape patent data for a single patent number.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False) # Set headless=False to visualize the browser
page = browser.new_page()
code
Assistant
User
add date of pantent and date of garny at end
Assistant
User
provide complte code
Assistant
User
Assistant
try:
# Visit website
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
print("Page loaded successfully.")
# Wait for the search form to load and fill details
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000) # Wait up to 60 seconds
page.fill('input[name="PatentNumber"]', patent_number)
# Wait for CAPTCHA to load and capture the image
page.wait_for_selector('#Captcha', timeout=60000)
captcha_element = page.locator('#Captcha')
captcha_path = 'captcha.png'
captcha_element.screenshot(path=captcha_path)
print("CAPTCHA image saved as captcha.png.")
# Solve the CAPTCHA (manual input for now)
captcha_text = solve_captcha(captcha_path)
# Fill the CAPTCHA and submit
page.fill('input[name="CaptchaText"]', captcha_text)
page.click('input[name="submit"]')
# Wait for the search results to load
page.wait_for_load_state('networkidle', timeout=60000) # Wait until network is idle
# Check for error message in case CAPTCHA/data is incorrect
error_message_locator = page.locator('.error-message, .alert-danger')
if error_message_locator.count() > 0:
print("Error:", error_message_locator.text_content().strip())
return None
print("Fetching Patent Data...")
# Extract key details now, ensuring relevant locators are robust
legal_status = safe_extract_text(page.locator('tr:has-text("Legal Status :") td:nth-child(2)'))
# Determine the type of date and get the date value
expiry_text = page.locator('tr:has-text("Date of Expiry :") td:nth-child(2)')
renewal_text = page.locator('tr:has-text("Due Date of Next Renewal :") td:nth-child(2)')
if expiry_text.count() > 0:
date_type = "Date of Expiry"
date_value = safe_extract_text(expiry_text)
else:
date_type = "Due Date of Next Renewal"
date_value = safe_extract_text(renewal_text)
# Extract patent and application numbers
patent_number_text = safe_extract_text(page.locator('tr:has-text("Patent Number") td:nth-child(3)'), default=patent_number)
application_number = safe_extract_text(page.locator('tr:has-text("Application Number") td:nth-child(3)'), default="N/A")
grant_title = safe_extract_text(page.locator('tr:has-text("Grant Title") td:nth-child(3), tr:has-text("Grant Title") td[colspan="4"]'))
patentee_name = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(2)'))
patentee_type = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(3)'))
# Extract last valid renewal details
renewal_table = page.locator('table#renual tbody')
row_count = renewal_table.locator('tr').count()
last_renewal_year = "N/A"
last_renewal_amount = "N/A"
last_renewal_date = "N/A"
for i in range(row_count - 1, 0, -1): # Iterate from the last row
row = renewal_table.locator('tr').nth(i)
columns = row.locator('td')
if columns.count() >= 8: # Ensure the row has enough columns
# Extract year, renewal amount, and renewal date
year = safe_extract_text(columns.nth(0)).replace('<sup>th</sup>', 'th')
renewal_amount = safe_extract_text(columns.nth(5)) # Column 6: Renewal Amount
renewal_date = safe_extract_text(columns.nth(7)) # Column 8: Date of Renewal
# Skip rows where the values are "--" or empty
if year and "--" not in (year, renewal_amount, renewal_date):
last_renewal_year = year
last_renewal_amount = renewal_amount
last_renewal_date = renewal_date
break
# Output the results
print(f"Legal Status: {legal_status}")
print(f"Date Type: {date_type}")
print(f"Date Value: {date_value}")
print(f"Patent Number: {patent_number_text}")
print(f"Application Number: {application_number}")
print(f"Grant Title: {grant_title}")
print(f"Name of Patentee: {patentee_name}")
print(f"Patentee Type: {patentee_type}")
print(f"Last Renewal Year: {last_renewal_year}")
print(f"Renewal Amount: {last_renewal_amount}")
print(f"Date of Renewal: {last_renewal_date}")
# Return results as a dictionary
return {
'Patent Number': patent_number_text,
'Application Number': application_number,
'Legal Status': legal_status,
'Date Type': date_type,
'Date Value': date_value,
'Grant Title': grant_title,
'Patentee Name': patentee_name,
'Patentee Type': patentee_type,
'Last Renewal Year': last_renewal_year,
'Renewal Amount': last_renewal_amount,
'Date of Renewal': last_renewal_date,
}
except Exception as e:
print("Error during scraping:", e)
return None
finally:
# Clean up the captcha file if it exists
if os.path.exists(captcha_path):
os.remove(captcha_path)
browser.close()
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a locator.
Returns a default value if extraction fails.
"""
try:
return locator.inner_html().strip() # Use .inner_html() to correctly handle HTML content like
except Exception:
return default
def save_to_csv(data, filename):
"""
Save a dictionary of data to a CSV file.
"""
if data:
file_exists = os.path.isfile(filename)
with open(filename, mode='a', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=data.keys())
code
# Write header only if the file doesn't already exist
if not file_exists:
writer.writeheader()
writer.writerow(data)
print(f"Data saved to {filename}")
else:
print("No data to save.")
if name == "main":
# Test for a single patent number
test_patent_number = "412823" # Replace with the actual patent number to test
print(f"Scraping data for Patent Number: {test_patent_number}")
scraped_data = scrape_patent_data(test_patent_number)
code
if scraped_data:
print("Scraping completed successfully. Saving data to CSV...")
save_to_csv(scraped_data, "patent_data2.csv")
else:
print("Failed to scrape patent details.") i will not type the captcha in treminal i want to directly typr in the text input
If you want to bypass typing the CAPTCHA in the terminal and instead type it directly into a text input provided by the webpage, you can edit the function responsible for solving the CAPTCHA to interact with the browser itself.
Here’s how you can implement this:
Instead of asking the user to type the CAPTCHA in the terminal with input(), you can focus the CAPTCHA input field in the browser and let the user type it directly in the webpage.
Keep the browser open for the manual CAPTCHA entry and wait for the user to manually perform the CAPTCHA-solving action before proceeding.
Here’s the modified version of your solve_captcha() function and how it fits into your scraping workflow:
Updated Code for CAPTCHA Handling:
python
def solve_captcha_directly_in_browser(page, captcha_image_path):
"""
Allow the user to solve the CAPTCHA directly in the browser.
The function pauses execution and waits for the user to manually
solve the CAPTCHA in the input field on the webpage.
"""
print("CAPTCHA displayed in the browser. Please solve it and press ENTER in the terminal to continue.")
captcha_element = page.locator('#Captcha')
captcha_element.screenshot(path=captcha_image_path) # Save CAPTCHA image (optional)
print(f"CAPTCHA image saved as: {captcha_image_path}")
# Wait here until the user presses Enter in the terminal after solving the CAPTCHA
input("Press ENTER after solving the CAPTCHA in the browser...")
print("Resuming script after CAPTCHA input.")
Updated scrape_patent_data Integration:
Replace the manual CAPTCHA-solving flow with the updated function inside scrape_patent_data:
python
# Solve the CAPTCHA directly in the browser by pausing the script
captcha_path = 'captcha.png'
solve_captcha_directly_in_browser(page, captcha_path)
Complete Integration:
Here’s the updated scrape_patent_data function:
python
Key Changes:
The CAPTCHA-solving process now pauses and lets the user interact directly with the browser to solve the CAPTCHA.
The program waits for the user to signal (by pressing ENTER in the terminal) before continuing the script execution.
This approach keeps the script functional while allowing you to manually solve the CAPTCHA directly within the browser, saving time and streamlining the process.
Here's how you can include the "Date of Patent" and "Date of Grant" fields at the end of the scraping process by extracting these details from the webpage. Below is how these dates can be handled and appended to your output dictionary.
Updated scrape_patent_data Function (with Date of Patent and Date of Grant):
python
def scrape_patent_data(patent_number):
"""
Scrape patent data for a single patent number.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False) # Set `headless=False` to visualize the browser
page = browser.new_page()
try:
# Visit website
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
print("Page loaded successfully.")
# Wait for the search form to load and fill details
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000) # Wait up to 60 seconds
page.fill('input[name="PatentNumber"]', patent_number)
# Wait for CAPTCHA to load and capture the image
page.wait_for_selector('#Captcha', timeout=60000)
captcha_path = 'captcha.png'
# Let the user solve the CAPTCHA directly in the browser
solve_captcha_directly_in_browser(page, captcha_path)
# After manual CAPTCHA entry, submit the form
page.click('input[name="submit"]')
# Wait for the search results to load
page.wait_for_load_state('networkidle', timeout=60000) # Wait until network is idle
# Check for error message in case CAPTCHA/data is incorrect
error_message_locator = page.locator('.error-message, .alert-danger')
if error_message_locator.count() > 0:
print("Error:", error_message_locator.text_content().strip())
return None
print("Fetching Patent Data...")
# Extract Legal Status
legal_status = safe_extract_text(page.locator('tr:has-text("Legal Status :") td:nth-child(2)'))
# Determine the type of date and get the value
expiry_text = page.locator('tr:has-text("Date of Expiry :") td:nth-child(2)')
renewal_text = page.locator('tr:has-text("Due Date of Next Renewal :") td:nth-child(2)')
if expiry_text.count() > 0:
date_type = "Date of Expiry"
date_value = safe_extract_text(expiry_text)
else:
date_type = "Due Date of Next Renewal"
date_value = safe_extract_text(renewal_text)
# Extract patent and application numbers
patent_number_text = safe_extract_text(page.locator('tr:has-text("Patent Number") td:nth-child(3)'), default=patent_number)
application_number = safe_extract_text(page.locator('tr:has-text("Application Number") td:nth-child(3)'), default="N/A")
# Grant-related details
grant_title = safe_extract_text(page.locator('tr:has-text("Grant Title") td:nth-child(3), tr:has-text("Grant Title") td[colspan="4"]'))
patentee_name = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(2)'))
patentee_type = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(3)'))
# Extract dates: Date of Patent and Date of Grant
date_of_patent = safe_extract_text(page.locator('tr:has-text("Date of Patent") td:nth-child(2)'))
date_of_grant = safe_extract_text(page.locator('tr:has-text("Date of Grant") td:nth-child(2)'))
# Extract last valid renewal details
renewal_table = page.locator('table#renual tbody')
row_count = renewal_table.locator('tr').count()
last_renewal_year = "N/A"
last_renewal_amount = "N/A"
last_renewal_date = "N/A"
for i in range(row_count - 1, 0, -1): # Iterate from the last row
row = renewal_table.locator('tr').nth(i)
columns = row.locator('td')
if columns.count() >= 8: # Ensure the row has enough columns
# Extract year, renewal amount, and renewal date
year = safe_extract_text(columns.nth(0)).replace('<sup>th</sup>', 'th')
renewal_amount = safe_extract_text(columns.nth(5)) # Column 6: Renewal Amount
renewal_date = safe_extract_text(columns.nth(7)) # Column 8: Date of Renewal
# Skip rows with "--" or empty values
if year and "--" not in (year, renewal_amount, renewal_date):
last_renewal_year = year
last_renewal_amount = renewal_amount
last_renewal_date = renewal_date
break
# Output the results
print(f"Legal Status: {legal_status}")
print(f"Date Type: {date_type}")
print(f"Date Value: {date_value}")
print(f"Patent Number: {patent_number_text}")
print(f"Application Number: {application_number}")
print(f"Grant Title: {grant_title}")
print(f"Name of Patentee: {patentee_name}")
print(f"Patentee Type: {patentee_type}")
print(f"Date of Patent: {date_of_patent}")
print(f"Date of Grant: {date_of_grant}")
print(f"Last Renewal Year: {last_renewal_year}")
print(f"Renewal Amount: {last_renewal_amount}")
print(f"Date of Renewal: {last_renewal_date}")
# Return results as a dictionary
return {
'Patent Number': patent_number_text,
'Application Number': application_number,
'Legal Status': legal_status,
'Date Type': date_type,
'Date Value': date_value,
'Grant Title': grant_title,
'Patentee Name': patentee_name,
'Patentee Type': patentee_type,
'Date of Patent': date_of_patent,
'Date of Grant': date_of_grant,
'Last Renewal Year': last_renewal_year,
'Renewal Amount': last_renewal_amount,
'Date of Renewal': last_renewal_date,
}
except Exception as e:
print("Error during scraping:", e)
return None
finally:
# Clean up the CAPTCHA file if it exists
if os.path.exists(captcha_path):
os.remove(captcha_path)
browser.close()
Explanation of Changes:
Date of Patent:
Added a locator for the row containing "Date of Patent" in the results table.
Extracted text from the corresponding <td> element.
python
date_of_patent = safe_extract_text(page.locator('tr:has-text("Date of Patent") td:nth-child(2)'))
Date of Grant:
Used a similar approach as "Date of Patent" to locate and extract "Date of Grant".
python
date_of_grant = safe_extract_text(page.locator('tr:has-text("Date of Grant") td:nth-child(2)'))
Appended Data to the Dictionary:
Included date_of_patent and date_of_grant fields at the end of the returned data dictionary.
Example Output Dictionary:
Here’s an example of the dictionary output for a successfully scraped patent:
python
{
'Patent Number': '412823',
'Application Number': '15453',
'Legal Status': 'Granted',
'Date Type': 'Date of Expiry',
'Date Value': '2027-02-15',
'Grant Title': 'Invention Title Example',
'Patentee Name': 'John Doe',
'Patentee Type': 'Individual',
'Date of Patent': '2023-03-10',
'Date of Grant': '2023-11-01',
'Last Renewal Year': '2023',
'Renewal Amount': '10000',
'Date of Renewal': '2023-10-30',
}
Save to CSV:
If you're using the provided save_to_csv utility, this function's behavior will remain the same. The new fields, Date of Patent and Date of Grant, will automatically be included as additional columns when saved to the CSV file.
Let me know if you need more assistance! 🚀
Here’s the complete code that includes all the modifications you requested. This version supports solving the CAPTCHA directly in the browser, extracts the required data (including Date of Patent and Date of Grant), and saves the data to a CSV file.
Complete Code
python
import os
import csv
from playwright.sync_api import sync_playwright
def solve_captcha_directly_in_browser(page, captcha_image_path):
"""
Allow the user to solve the CAPTCHA directly in the browser.
The function pauses execution and waits for the user to manually
solve the CAPTCHA in the input field on the webpage.
"""
print("CAPTCHA displayed in the browser. Please solve it and press ENTER in the terminal to continue.")
captcha_element = page.locator('#Captcha')
captcha_element.screenshot(path=captcha_image_path) # Save CAPTCHA image (optional)
print(f"CAPTCHA image saved as: {captcha_image_path}")
# Wait here until the user presses Enter in the terminal after solving the CAPTCHA
input("Press ENTER after solving the CAPTCHA in the browser...")
print("Resuming script after CAPTCHA input.")
def scrape_patent_data(patent_number):
"""
Scrape patent data for a single patent number.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False) # Set `headless=False` to visualize the browser
page = browser.new_page()
try:
# Visit website
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
print("Page loaded successfully.")
# Wait for the search form to load and fill details
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000) # Wait up to 60 seconds
page.fill('input[name="PatentNumber"]', patent_number)
# Wait for CAPTCHA to load and capture the image
page.wait_for_selector('#Captcha', timeout=60000)
captcha_path = 'captcha.png'
# Let the user solve the CAPTCHA directly in the browser
solve_captcha_directly_in_browser(page, captcha_path)
# After manual CAPTCHA entry, submit the form
page.click('input[name="submit"]')
# Wait for the search results to load
page.wait_for_load_state('networkidle', timeout=60000) # Wait until network is idle
# Check for error message in case CAPTCHA/data is incorrect
error_message_locator = page.locator('.error-message, .alert-danger')
if error_message_locator.count() > 0:
print("Error:", error_message_locator.text_content().strip())
return None
print("Fetching Patent Data...")
# Extract Legal Status
legal_status = safe_extract_text(page.locator('tr:has-text("Legal Status :") td:nth-child(2)'))
# Determine the type of date and get the value
expiry_text = page.locator('tr:has-text("Date of Expiry :") td:nth-child(2)')
renewal_text = page.locator('tr:has-text("Due Date of Next Renewal :") td:nth-child(2)')
if expiry_text.count() > 0:
date_type = "Date of Expiry"
date_value = safe_extract_text(expiry_text)
else:
date_type = "Due Date of Next Renewal"
date_value = safe_extract_text(renewal_text)
# Extract patent and application numbers
patent_number_text = safe_extract_text(page.locator('tr:has-text("Patent Number") td:nth-child(3)'), default=patent_number)
application_number = safe_extract_text(page.locator('tr:has-text("Application Number") td:nth-child(3)'), default="N/A")
# Grant-related details
grant_title = safe_extract_text(page.locator('tr:has-text("Grant Title") td:nth-child(3), tr:has-text("Grant Title") td[colspan="4"]'))
patentee_name = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(2)'))
patentee_type = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(3)'))
# Extract dates: Date of Patent and Date of Grant
date_of_patent = safe_extract_text(page.locator('tr:has-text("Date of Patent") td:nth-child(2)'))
date_of_grant = safe_extract_text(page.locator('tr:has-text("Date of Grant") td:nth-child(2)'))
# Extract last valid renewal details
renewal_table = page.locator('table#renual tbody')
row_count = renewal_table.locator('tr').count()
last_renewal_year = "N/A"
last_renewal_amount = "N/A"
last_renewal_date = "N/A"
for i in range(row_count - 1, 0, -1): # Iterate from the last row
row = renewal_table.locator('tr').nth(i)
columns = row.locator('td')
if columns.count() >= 8: # Ensure the row has enough columns
# Extract year, renewal amount, and renewal date
year = safe_extract_text(columns.nth(0)).replace('<sup>th</sup>', 'th')
renewal_amount = safe_extract_text(columns.nth(5)) # Column 6: Renewal Amount
renewal_date = safe_extract_text(columns.nth(7)) # Column 8: Date of Renewal
# Skip rows with "--" or empty values
if year and "--" not in (year, renewal_amount, renewal_date):
last_renewal_year = year
last_renewal_amount = renewal_amount
last_renewal_date = renewal_date
break
# Output the results
print(f"Legal Status: {legal_status}")
print(f"Date Type: {date_type}")
print(f"Date Value: {date_value}")
print(f"Patent Number: {patent_number_text}")
print(f"Application Number: {application_number}")
print(f"Grant Title: {grant_title}")
print(f"Name of Patentee: {patentee_name}")
print(f"Patentee Type: {patentee_type}")
print(f"Date of Patent: {date_of_patent}")
print(f"Date of Grant: {date_of_grant}")
print(f"Last Renewal Year: {last_renewal_year}")
print(f"Renewal Amount: {last_renewal_amount}")
print(f"Date of Renewal: {last_renewal_date}")
# Return results as a dictionary
return {
'Patent Number': patent_number_text,
'Application Number': application_number,
'Legal Status': legal_status,
'Date Type': date_type,
'Date Value': date_value,
'Grant Title': grant_title,
'Patentee Name': patentee_name,
'Patentee Type': patentee_type,
'Date of Patent': date_of_patent,
'Date of Grant': date_of_grant,
'Last Renewal Year': last_renewal_year,
'Renewal Amount': last_renewal_amount,
'Date of Renewal': last_renewal_date,
}
except Exception as e:
print("Error during scraping:", e)
return None
finally:
# Clean up the CAPTCHA file if it exists
if os.path.exists(captcha_path):
os.remove(captcha_path)
browser.close()
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a locator.
Returns a default value if extraction fails.
"""
try:
return locator.inner_html().strip() # Use `.inner_html()` to correctly handle HTML content like <sup>
except Exception:
return default
def save_to_csv(data, filename):
"""
Save a dictionary of data to a CSV file.
"""
if data:
file_exists = os.path.isfile(filename)
with open(filename, mode='a', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=data.keys())
# Write header only if the file doesn't already exist
if not file_exists:
writer.writeheader()
writer.writerow(data)
print(f"Data saved to {filename}")
else:
print("No data to save.")
if __name__ == "__main__":
# Test for a single patent number
test_patent_number = "412823" # Replace with the actual patent number to test
print(f"Scraping data for Patent Number: {test_patent_number}")
scraped_data = scrape_patent_data(test_patent_number)
if scraped_data:
print("Scraping completed successfully. Saving data to CSV...")
save_to_csv(scraped_data, "patent_data.csv")
else:
print("Failed to scrape patent details.")
Key Features:
Allows manual CAPTCHA solving directly in the browser.
Extracts key fields, including:
Patent Number
Application Number
Legal Status
Date of Expiry/Due Date of Next Renewal
Date of Patent
Date of Grant
Grant Title, Patentee Name, and Patentee Type
Last Renewal Year, Renewal Amount, and Renewal Date
Saves the scraped results in a CSV file (patent_data.csv).
You can test this code with real patent numbers and adjust the field locators if needed to ensure compatibility with the website's structure.
Let me know if you need further assistance! 🚀
take excel sheet and write incsv file import os
import csv
from playwright.sync_api import sync_playwright
def solve_captcha_directly_in_browser(page, captcha_image_path):
"""
Allow the user to solve the CAPTCHA directly in the browser.
The function pauses execution and waits for the user to manually
solve the CAPTCHA in the input field on the webpage.
"""
print("CAPTCHA displayed in the browser. Please solve it and press ENTER in the terminal to continue.")
captcha_element = page.locator('#Captcha')
captcha_element.screenshot(path=captcha_image_path) # Save CAPTCHA image (optional)
print(f"CAPTCHA image saved as: {captcha_image_path}")
code
# Wait here until the user presses Enter in the terminal after solving the CAPTCHA
input("Press ENTER after solving the CAPTCHA in the browser...")
print("Resuming script after CAPTCHA input.")
def scrape_patent_data(patent_number):
"""
Scrape patent data for a single patent number.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False) # Set headless=False to visualize the browser
page = browser.new_page()
code
try:
# Visit website
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
print("Page loaded successfully.")
# Wait for the search form to load and fill details
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000) # Wait up to 60 seconds
page.fill('input[name="PatentNumber"]', patent_number)
# Wait for CAPTCHA to load and capture the image
page.wait_for_selector('#Captcha', timeout=60000)
captcha_path = 'captcha.png'
# Let the user solve the CAPTCHA directly in the browser
solve_captcha_directly_in_browser(page, captcha_path)
# After manual CAPTCHA entry, submit the form
page.click('input[name="submit"]')
# Wait for the search results to load
page.wait_for_load_state('networkidle', timeout=60000) # Wait until network is idle
# Check for error message in case CAPTCHA/data is incorrect
error_message_locator = page.locator('.error-message, .alert-danger')
if error_message_locator.count() > 0:
print("Error:", error_message_locator.text_content().strip())
return None
print("Fetching Patent Data...")
# Extract Legal Status
legal_status = safe_extract_text(page.locator('tr:has-text("Legal Status :") td:nth-child(2)'))
# Determine the type of date and get the value
expiry_text = page.locator('tr:has-text("Date of Expiry :") td:nth-child(2)')
renewal_text = page.locator('tr:has-text("Due Date of Next Renewal :") td:nth-child(2)')
if expiry_text.count() > 0:
date_type = "Date of Expiry"
date_value = safe_extract_text(expiry_text)
else:
date_type = "Due Date of Next Renewal"
date_value = safe_extract_text(renewal_text)
# Extract patent and application numbers
patent_number_text = safe_extract_text(page.locator('tr:has-text("Patent Number") td:nth-child(3)'), default=patent_number)
application_number = safe_extract_text(page.locator('tr:has-text("Application Number") td:nth-child(3)'), default="N/A")
# Grant-related details
grant_title = safe_extract_text(page.locator('tr:has-text("Grant Title") td:nth-child(3), tr:has-text("Grant Title") td[colspan="4"]'))
patentee_name = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(2)'))
patentee_type = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(3)'))
# Extract dates: Date of Patent and Date of Grant
date_of_patent = safe_extract_text(page.locator('tr:has-text("Date of Patent") td:nth-child(2)'))
date_of_grant = safe_extract_text(page.locator('tr:has-text("Date of Grant") td:nth-child(2)'))
# Extract last valid renewal details
renewal_table = page.locator('table#renual tbody')
row_count = renewal_table.locator('tr').count()
last_renewal_year = "N/A"
last_renewal_amount = "N/A"
last_renewal_date = "N/A"
for i in range(row_count - 1, 0, -1): # Iterate from the last row
row = renewal_table.locator('tr').nth(i)
columns = row.locator('td')
if columns.count() >= 8: # Ensure the row has enough columns
# Extract year, renewal amount, and renewal date
year = safe_extract_text(columns.nth(0)).replace('<sup>th</sup>', 'th')
renewal_amount = safe_extract_text(columns.nth(5)) # Column 6: Renewal Amount
renewal_date = safe_extract_text(columns.nth(7)) # Column 8: Date of Renewal
# Skip rows with "--" or empty values
if year and "--" not in (year, renewal_amount, renewal_date):
last_renewal_year = year
last_renewal_amount = renewal_amount
last_renewal_date = renewal_date
break
# Output the results
print(f"Legal Status: {legal_status}")
print(f"Date Type: {date_type}")
print(f"Date Value: {date_value}")
print(f"Patent Number: {patent_number_text}")
print(f"Application Number: {application_number}")
print(f"Grant Title: {grant_title}")
print(f"Name of Patentee: {patentee_name}")
print(f"Patentee Type: {patentee_type}")
print(f"Date of Patent: {date_of_patent}")
print(f"Date of Grant: {date_of_grant}")
print(f"Last Renewal Year: {last_renewal_year}")
print(f"Renewal Amount: {last_renewal_amount}")
print(f"Date of Renewal: {last_renewal_date}")
# Return results as a dictionary
return {
'Patent Number': patent_number_text,
'Application Number': application_number,
'Legal Status': legal_status,
'Date Type': date_type,
'Date Value': date_value,
'Grant Title': grant_title,
'Patentee Name': patentee_name,
'Patentee Type': patentee_type,
'Date of Patent': date_of_patent,
'Date of Grant': date_of_grant,
'Last Renewal Year': last_renewal_year,
'Renewal Amount': last_renewal_amount,
'Date of Renewal': last_renewal_date,
}
except Exception as e:
print("Error during scraping:", e)
return None
finally:
# Clean up the CAPTCHA file if it exists
if os.path.exists(captcha_path):
os.remove(captcha_path)
browser.close()
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a locator.
Returns a default value if extraction fails.
"""
try:
return locator.inner_html().strip() # Use .inner_html() to correctly handle HTML content like
except Exception:
return default
def save_to_csv(data, filename):
"""
Save a dictionary of data to a CSV file.
"""
if data:
file_exists = os.path.isfile(filename)
with open(filename, mode='a', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=data.keys())
code
# Write header only if the file doesn't already exist
if not file_exists:
writer.writeheader()
writer.writerow(data)
print(f"Data saved to {filename}")
else:
print("No data to save.")
if name == "main":
# Test for a single patent number
test_patent_number = "412823" # Replace with the actual patent number to test
print(f"Scraping data for Patent Number: {test_patent_number}")
scraped_data = scrape_patent_data(test_patent_number)
code
if scraped_data:
print("Scraping completed successfully. Saving data to CSV...")
save_to_csv(scraped_data, "patent_data.csv")
else:
print("Failed to scrape patent details.") compltete code
Below is the enhanced complete code that includes the functionality of reading a list of patent numbers from an Excel file, scraping the data for each patent, and writing the consolidated results to a CSV file.
Full Code: Read Excel, Scrape Data, and Save to CSV
You will need to install two Python libraries: pandas for handling the Excel file and playwright for web scraping.
Install required libraries:
bash
pip install pandas playwright
playwright install
Now, here's the full script:
python
import os
import csv
import pandas as pd
from playwright.sync_api import sync_playwright
def solve_captcha_directly_in_browser(page, captcha_image_path):
"""
Allow the user to solve the CAPTCHA directly in the browser.
Pause execution and wait for the user to manually solve it.
"""
print("CAPTCHA displayed in the browser. Please solve it and press ENTER in the terminal to continue.")
captcha_element = page.locator('#Captcha')
captcha_element.screenshot(path=captcha_image_path) # Save CAPTCHA image (optional)
print(f"CAPTCHA image saved as: {captcha_image_path}")
# Wait for the user to press Enter after solving the CAPTCHA
input("Press ENTER after solving the CAPTCHA in the browser...")
print("Resuming script after CAPTCHA input.")
def scrape_patent_data(patent_number):
"""
Scrape patent data for a single patent number.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False) # Set `headless=False` to visualize the browser
page = browser.new_page()
try:
# Visit website
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
print(f"Page loaded successfully for Patent Number: {patent_number}")
# Wait for the search form to load and fill details
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000)
page.fill('input[name="PatentNumber"]', patent_number)
# Wait for CAPTCHA to load
page.wait_for_selector('#Captcha', timeout=60000)
captcha_path = 'captcha.png'
# Solve the CAPTCHA directly in the browser
solve_captcha_directly_in_browser(page, captcha_path)
# After manual CAPTCHA entry, submit the form
page.click('input[name="submit"]')
# Wait for the search results to load
page.wait_for_load_state('networkidle', timeout=60000)
# Check for error message in case CAPTCHA/data is incorrect
error_message_locator = page.locator('.error-message, .alert-danger')
if error_message_locator.count() > 0:
print(f"Error for Patent Number {patent_number}: {error_message_locator.text_content().strip()}")
return {'Patent Number': patent_number, 'Error': 'CAPTCHA or data error'}
# Extract legal status
legal_status = safe_extract_text(page.locator('tr:has-text("Legal Status :") td:nth-child(2)'))
# Extract type of date and date value
expiry_text = page.locator('tr:has-text("Date of Expiry :") td:nth-child(2)')
renewal_text = page.locator('tr:has-text("Due Date of Next Renewal :") td:nth-child(2)')
if expiry_text.count() > 0:
date_type = "Date of Expiry"
date_value = safe_extract_text(expiry_text)
else:
date_type = "Due Date of Next Renewal"
date_value = safe_extract_text(renewal_text)
# Extract patent and application numbers
patent_number_text = safe_extract_text(page.locator('tr:has-text("Patent Number") td:nth-child(3)'), default=patent_number)
application_number = safe_extract_text(page.locator('tr:has-text("Application Number") td:nth-child(3)'), default="N/A")
# Extract grant-related information
grant_title = safe_extract_text(page.locator('tr:has-text("Grant Title") td:nth-child(3), tr:has-text("Grant Title") td[colspan="4"]'))
patentee_name = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(2)'))
patentee_type = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(3)'))
# Extract important dates
date_of_patent = safe_extract_text(page.locator('tr:has-text("Date of Patent") td:nth-child(2)'))
date_of_grant = safe_extract_text(page.locator('tr:has-text("Date of Grant") td:nth-child(2)'))
# Extract last renewal details
renewal_table = page.locator('table#renual tbody')
row_count = renewal_table.locator('tr').count()
last_renewal_year = "N/A"
last_renewal_amount = "N/A"
last_renewal_date = "N/A"
for i in range(row_count - 1, 0, -1): # Iterate from the last row
row = renewal_table.locator('tr').nth(i)
columns = row.locator('td')
if columns.count() >= 8: # Ensure the row has enough columns
year = safe_extract_text(columns.nth(0)).replace('<sup>th</sup>', 'th')
renewal_amount = safe_extract_text(columns.nth(5)) # Column 6: Renewal Amount
renewal_date = safe_extract_text(columns.nth(7)) # Column 8: Date of Renewal
# Skip rows with "--" or empty values
if year and "--" not in (year, renewal_amount, renewal_date):
last_renewal_year = year
last_renewal_amount = renewal_amount
last_renewal_date = renewal_date
break
# Return results as a dictionary
return {
'Patent Number': patent_number_text,
'Application Number': application_number,
'Legal Status': legal_status,
'Date Type': date_type,
'Date Value': date_value,
'Grant Title': grant_title,
'Patentee Name': patentee_name,
'Patentee Type': patentee_type,
'Date of Patent': date_of_patent,
'Date of Grant': date_of_grant,
'Last Renewal Year': last_renewal_year,
'Renewal Amount': last_renewal_amount,
'Date of Renewal': last_renewal_date,
}
except Exception as e:
print(f"Error during scraping for Patent Number {patent_number}:", e)
return {'Patent Number': patent_number, 'Error': str(e)}
finally:
# Clean up captcha image file
if os.path.exists(captcha_path):
os.remove(captcha_path)
browser.close()
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a locator. Return a default if extraction fails.
"""
try:
return locator.inner_html().strip()
except Exception:
return default
def save_to_csv(data_list, filename):
"""
Save a list of dictionaries to a CSV file.
"""
if data_list:
file_exists = os.path.isfile(filename)
with open(filename, mode='w' if not file_exists else 'a', newline='', encoding='utf-8') as file:
writer = csv.DictWriter(file, fieldnames=data_list[0].keys())
# Write header only if the file doesn't exist
if not file_exists:
writer.writeheader()
writer.writerows(data_list)
print(f"Data saved to {filename}")
if __name__ == "__main__":
# Load patent numbers from an Excel file
excel_filename = "patent_numbers.xlsx" # Replace with your Excel file
csv_filename = "patent_data.csv"
print(f"Reading patent numbers from {excel_filename}...")
try:
df = pd.read_excel(excel_filename)
patent_numbers = df['Patent Number'].astype(str).tolist() # Ensure they're strings
except Exception as e:
print(f"Error reading Excel file: {e}")
exit()
# Scrape details for each patent number
scraped_data_list = []
for patent_number in patent_numbers:
print(f"Scraping data for Patent Number: {patent_number}...")
scraped_data = scrape_patent_data(patent_number)
if scraped_data:
scraped_data_list.append(scraped_data)
# Save all scraped data to CSV
if scraped_data_list:
print("Saving all scraped data to CSV...")
save_to_csv(scraped_data_list, csv_filename)
else:
print("No data scraped, nothing to save.")
Explanation of the Code:
Read Patent Numbers from Excel:
Reads an Excel file (patent_numbers.xlsx) into a Pandas DataFrame.
Extracts the Patent Number column from the Excel file into a list.
Web Scraping for Each Patent:
For each patent number in the list, the scraping process is executed.
Captures key details like legal status, type of date (expiry/renewal), patentee info, etc.
Handles CAPTCHA by letting the user manually enter it in the browser.
Save Results to CSV:
Writes all scraped data to a CSV file (patent_data.csv) for further use.
Steps to Run the Code:
Prepare an Excel file (patent_numbers.xlsx) with a column named Patent Number.
Install required libraries with:
bash
pip install pandas playwright
playwright install
Execute the script. It will open a browser for each patent and allow you to resolve CAPTCHAs manually.
Let me know if you encounter any issues or need additional features! 🚀
def scrape_patent_data(patent_number):
"""
Scrape patent data for a single patent number.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False) # Set `headless=False` to visualize the browser
page = browser.new_page()
try:
# Visit website
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
print("Page loaded successfully.")
# Wait for the search form to load and fill details
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000) # Wait up to 60 seconds
page.fill('input[name="PatentNumber"]', patent_number)
# Wait for CAPTCHA to load and capture the image
page.wait_for_selector('#Captcha', timeout=60000)
captcha_path = 'captcha.png'
# Let the user solve the CAPTCHA directly in the browser
solve_captcha_directly_in_browser(page, captcha_path)
# After manual CAPTCHA entry, submit the form
page.click('input[name="submit"]')
# Wait for the search results to load
page.wait_for_load_state('networkidle', timeout=60000) # Wait until network is idle
# Check for error message in case CAPTCHA/data is incorrect
error_message_locator = page.locator('.error-message, .alert-danger')
if error_message_locator.count() > 0:
print("Error:", error_message_locator.text_content().strip())
return None
print("Fetching Patent Data...")
# Extract data as before...
legal_status = safe_extract_text(page.locator('tr:has-text("Legal Status :") td:nth-child(2)'))
# Determine the type of date
expiry_text = page.locator('tr:has-text("Date of Expiry :") td:nth-child(2)')
renewal_text = page.locator('tr:has-text("Due Date of Next Renewal :") td:nth-child(2)')
if expiry_text.count() > 0:
date_type = "Date of Expiry"
date_value = safe_extract_text(expiry_text)
else:
date_type = "Due Date of Next Renewal"
date_value = safe_extract_text(renewal_text)
# Extract patent and application numbers
patent_number_text = safe_extract_text(page.locator('tr:has-text("Patent Number") td:nth-child(3)'), default=patent_number)
application_number = safe_extract_text(page.locator('tr:has-text("Application Number") td:nth-child(3)'), default="N/A")
grant_title = safe_extract_text(page.locator('tr:has-text("Grant Title") td:nth-child(3), tr:has-text("Grant Title") td[colspan="4"]'))
patentee_name = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(2)'))
patentee_type = safe_extract_text(page.locator('table:has-text("Name of Patentee") tr:nth-child(2) td:nth-child(3)'))
# Extract last valid renewal details
renewal_table = page.locator('table#renual tbody')
row_count = renewal_table.locator('tr').count()
last_renewal_year = "N/A"
last_renewal_amount = "N/A"
last_renewal_date = "N/A"
for i in range(row_count - 1, 0, -1): # Iterate from the last row
row = renewal_table.locator('tr').nth(i)
columns = row.locator('td')
if columns.count() >= 8: # Ensure the row has enough columns
# Extract year, renewal amount, and renewal date
year = safe_extract_text(columns.nth(0)).replace('<sup>th</sup>', 'th')
renewal_amount = safe_extract_text(columns.nth(5)) # Column 6: Renewal Amount
renewal_date = safe_extract_text(columns.nth(7)) # Column 8: Date of Renewal
# Skip rows where the values are "--" or empty
if year and "--" not in (year, renewal_amount, renewal_date):
last_renewal_year = year
last_renewal_amount = renewal_amount
last_renewal_date = renewal_date
break
# Output the results
print(f"Legal Status: {legal_status}")
print(f"Date Type: {date_type}")
print(f"Date Value: {date_value}")
print(f"Patent Number: {patent_number_text}")
print(f"Application Number: {application_number}")
print(f"Grant Title: {grant_title}")
print(f"Name of Patentee: {patentee_name}")
print(f"Patentee Type: {patentee_type}")
print(f"Last Renewal Year: {last_renewal_year}")
print(f"Renewal Amount: {last_renewal_amount}")
print(f"Date of Renewal: {last_renewal_date}")
# Return results as a dictionary
return {
'Patent Number': patent_number_text,
'Application Number': application_number,
'Legal Status': legal_status,
'Date Type': date_type,
'Date Value': date_value,
'Grant Title': grant_title,
'Patentee Name': patentee_name,
'Patentee Type': patentee_type,
'Last Renewal Year': last_renewal_year,
'Renewal Amount': last_renewal_amount,
'Date of Renewal': last_renewal_date,
}
except Exception as e:
print("Error during scraping:", e)
return None
finally:
# Clean up the captcha file if it exists
if os.path.exists(captcha_path):
os.remove(captcha_path)
browser.close()