def scrape_patent_data(patent_number):
"""
Scrape patent data for a single patent number.
Fetches details like Legal Status, Patent Number, Application Number, Dates, etc.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
code
try:
os.makedirs(PDF_DIRECTORY, exist_ok=True)
print(f"Visiting the website for patent number: {patent_number}")
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000)
page.fill('input[name="PatentNumber"]', patent_number)
print("Please enter the CAPTCHA manually in the browser and submit the form.")
page.wait_for_url(TARGET_PAGE_URL, timeout=90000)
if page.locator("text=Sorry, we can't load the resource").is_visible():
print(f"Failed to load data for patent number {patent_number}: Sorry, we can't load the resource")
return {"Patent Number": patent_number, "Status": "Resource Not Loaded"}
print(f"Successfully loaded e-Register page for patent number {patent_number}.")
pdf_path = os.path.join(PDF_DIRECTORY, f"{patent_number}.pdf")
page.pdf(path=pdf_path)
print(f"PDF saved: {pdf_path}")
legal_status = safe_extract_text(page.locator('tr:has-text("Legal Status :") td:nth-child(2)'))
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)
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")
#date_of_patent = safe_extract_text(page.locator('tr:has-text("Date of Patent") td:nth-child(3)'), default="N/A")
application_number = safe_extract_text(page.locator('tr:has-text("Date of Grant") td:nth-child(3)'), default="N/A")
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)'))
date_of_patent = safe_extract_text(page.locator('tr:has-text("Date of Patent") td:nth-child(6)'))
date_of_grant = safe_extract_text(page.locator('tr:has-text("Date of Grant") td:nth-child(6)'))
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:
year = safe_extract_text(columns.nth(0)).replace('<sup>th</sup>', 'th')
renewal_amount = safe_extract_text(columns.nth(5))
renewal_date = safe_extract_text(columns.nth(7))
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 the fetched details
return {
'Patent Number': patent_number_text,
'Application Number': application_number,
'Legal Status': legal_status,
'Date Type': date_type,
'Date Value': date_value,
'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,
'Date of Patent': date_of_patent,
'Date of Grant': date_of_grant
}
except Exception as e:
print(f"Error during scraping for patent number {patent_number}: {e}")
return {"Patent Number": patent_number, "Status": "Error", "Error Message": str(e)}
finally:
browser.close()
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a Playwright locator.
"""
try:
return locator.inner_text().strip()
except Exception:
return default
def save_to_csv(data, filename):
"""
Append 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())
if not file_exists:
writer.writeheader()
writer.writerow(data)
if name == "main":
input_file = r"C:\Users\Administrator\Downloads\Sample-Data-PatAnn.xlsx"
output_file = "data3.csv"
code
print("Reading patent numbers from Excel file...")
df = pd.read_excel(input_file)
if 'Patent No.' not in df.columns:
print("Column 'Patent No.' not found in Excel file.")
exit()
# Process each patent number
for idx, row in df.iterrows():
patent_number = str(row['Patent No.'])
print(f"\nProcessing patent number: {patent_number}")
scraped_data = scrape_patent_data(patent_number)
print(f"Saving extracted data for patent number {patent_number}...")
save_to_csv(scraped_data, output_file) in this code when it is taking number from excel it is takinng as 243649.0 and also in pdf name it is .0pdf i want olnly 6 didgit
Assistant
To handle the issue where the patent numbers are read from the Excel file with decimal points (like 243649.0) and saved as filenames with a .0 suffix (like 243649.0.pdf), you can modify the code to format the patent numbers correctly. Here’s how you can do it:
Strip off any decimal parts and convert the patent number to a string with zero padding if necessary.
Ensure that the patent number is used as an integer value when naming the PDF file.
Here is a modified version of your code that incorporates these changes:
python
User
import os
import csv
import pandas as pd
from playwright.sync_api import sync_playwright
from PyPDF2 import PdfReader
from fpdf import FPDF
from PIL import Image
from io import BytesIO
import fitz
def create_pdf_a6(input_pdf_path, output_4_per_page):
"""
Create a PDF with 4 pages per A6 sheet.
"""
doc = fitz.open(input_pdf_path)
pdf_4_per_page = FPDF()
code
for i in range(0, len(doc), 4):
pdf_4_per_page.add_page()
for j in range(4):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
buffer = BytesIO()
img.save(buffer, format="PNG")
buffer.seek(0)
# Calculate position for A6
x_offset = (j % 2) * 105
y_offset = (j // 2) * 148.5
pdf_4_per_page.image(buffer, x=x_offset, y=y_offset, w=105, h=148.5)
pdf_4_per_page.output(output_4_per_page)
print(f"A6 PDF saved at: {output_4_per_page}")
def create_pdf_a5(input_pdf_path, output_2_per_page_landscape):
"""
Create a PDF with 2 pages per A5 sheet in landscape orientation.
"""
doc = fitz.open(input_pdf_path)
pdf_2_per_page_landscape = FPDF(orientation="L", unit="mm", format="A5")
code
for i in range(0, len(doc), 2):
pdf_2_per_page_landscape.add_page()
for j in range(2):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
buffer = BytesIO()
img.save(buffer, format="PNG")
buffer.seek(0)
# Calculate position for A5 landscape
x_offset = j * 148.5 # Half of A5 width
y_offset = 0
pdf_2_per_page_landscape.image(buffer, x=x_offset, y=y_offset, w=148.5, h=210)
pdf_2_per_page_landscape.output(output_2_per_page_landscape)
print(f"A5 Landscape PDF saved at: {output_2_per_page_landscape}")
Assistant
In the code you provided, the two combined PDF files (combined_A6.pdf and combined_A5.pdf) are being saved to the following directory:
code
C:\Users\Administrator\Desktop\webscrapper\
Explanation of the Code
PDF Files Directory:
The pdf_directory variable is set to store individual patent PDFs:
The combined PDFs will be saved directly on your Desktop in the specified folder (webscrapper):
combined_A6.pdf will contain 4 pages per A6 sheet.
combined_A5.pdf will contain 2 pages per A5 sheet in landscape orientation.
How to Find the Files
After your code has finished executing, go to your Desktop and look for the folder named webscrapper. Inside that folder, you should see combined_A6.pdf and combined_A5.pdf.
If Files Are Not There
If you do not see the files:
Make sure your script executed without any errors.
Check if the function create_pdf_a6() and create_pdf_a5() were called properly.
Ensure that the paths specified in the code are accessible and that you have permission to write to these locations.
Additional Tips
You can add print statements right after the PDF creation calls to confirm whether or not these functions executed and where the files were intended to be saved. This gives a clearer debug trail.
User
not getting these files after execution..add some debug staements
Assistant
To help you debug the issue with the creation of the combined PDF files, we can add print statements throughout the relevant parts of the code. This will give you more visibility into the program's execution flow and help you pinpoint where things might be going wrong. Here's how you can modify the code to include these debug statements:
python
User
Processing patent number: 373248
Visiting the website for patent number: 373248
Please enter the CAPTCHA manually in the browser and submit the form.
Successfully loaded e-Register page for patent number 373248.
PDF saved: C:\Users\Administrator\Desktop\webscrapper\pdfs\373248.pdf
PDF for patent number 373248 saved at: C:\Users\Administrator\Desktop\webscrapper\pdfs\373248.pdf
Saving extracted data for patent number 373248.. getting this only not co,mbiined
Assistant
From your description, it looks like the individual PDFs are being created and saved successfully, but the combined PDF files (combined_A6.pdf and combined_A5.pdf) are not being generated, or the code for combining the PDFs is not executing properly after processing all patent numbers.
Let's modify the code to ensure that the combined PDF creation functions are properly called and that you're notified in the console about their execution and status.
Updated Code with Additional Debug Statements
Here's how you can implement further debug statements and checks in your code:
python
User
i want that the pdf for one patent number to be saved on A5 sheet ..like if its 2 page ...save on A5 if its more than that save on A6 ....for each patent number
Assistant
To save the PDF for each patent number to a separate A5 or A6 sheet based on the number of pages, you can modify the code to check the number of pages in the PDF generated for each patent. If it's 1 or 2 pages, save it on an A5 sheet. If there are more than 2 pages, save it on an A6 sheet.
Here’s how you can implement this:
Check the number of pages after saving the patent PDF.
Use the appropriate function to save the PDF in the desired format.
Modified Code
Below is the updated part of the code that includes the logic to decide between saving to A5 or A6 based on the number of pages.
python
if __name__ == "__main__":
input_file = r"C:\Users\Administrator\Desktop\webscrapper\o1mini\Sample-Data-PatAnn.xlsx"
output_file = "data3.csv"
pdf_directory = "C:\\Users\\Administrator\\Desktop\\webscrapper\\pdfs"
os.makedirs(pdf_directory, exist_ok=True)
print("Reading patent numbers from Excel file...")
df = pd.read_excel(input_file)
if 'Patent No.' not in df.columns:
print("Column 'Patent No.' not found in Excel file.")
exit()
pdf_files = []
for idx, row in df.iterrows():
patent_number = str(row['Patent No.'])
print(f"\nProcessing patent number: {patent_number}")
pdf_path = os.path.join(pdf_directory, f"{patent_number}.pdf")
scraped_data = scrape_patent_data(patent_number, pdf_path)
if scraped_data:
num_pages = get_pdf_page_count(scraped_data) # Get the number of pages in the created PDF
print(f"Patent number {patent_number} PDF has {num_pages} page(s).")
if num_pages <= 2:
# Save as A5
print(f"Saving {patent_number} PDF to A5 format.")
create_pdf_a5(pdf_path, os.path.join(pdf_directory, f"{patent_number}_A5.pdf"))
else:
# Save as A6
print(f"Saving {patent_number} PDF to A6 format.")
create_pdf_a6(pdf_path, os.path.join(pdf_directory, f"{patent_number}_A6.pdf"))
pdf_files.append(scraped_data)
print(f"PDF for patent number {patent_number} saved at: {scraped_data}")
print(f"Saving extracted data for patent number {patent_number}...")
save_to_csv({
'Patent Number': patent_number,
'PDF Path': scraped_data
}, output_file)
print("All patents processed.")
print(f"Total number of PDFs created: {len(pdf_files)}")
print("Script execution completed.")
def get_pdf_page_count(pdf_path):
"""
Get the number of pages in a PDF file.
"""
with open(pdf_path, "rb") as f:
reader = PdfReader(f)
return len(reader.pages)
User
provide compleete upadted code
Assistant
Sure! Here’s the complete updated code that will handle the saving of patent PDFs in A5 or A6 format based on the number of pages for each patent number. This includes the necessary imports, functions, and the main execution block.
Processing patent number: 373248
Visiting the website for patent number: 373248
Please enter the CAPTCHA manually in the browser and submit the form.
Successfully loaded e-Register page for patent number 373248.
PDF saved: C:\Users\Administrator\Desktop\webscrapper\pdfs\373248.pdf
Patent number 373248 PDF has 2 page(s).
Saving 373248 PDF to A5 format.
Creating A5 format PDF from: C:\Users\Administrator\Desktop\webscrapper\pdfs\373248.pdf
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\webscrapper\PdfDataExtraction\main6.py", line 169, in
create_pdf_a5(pdf_path, os.path.join(pdf_directory, f"{patent_number}_A5.pdf"))
File "C:\Users\Administrator\Desktop\webscrapper\PdfDataExtraction\main6.py", line 65, in create_pdf_a5
pdf_2_per_page_landscape.image(buffer, x=x_offset, y=y_offset, w=148.5, h=210)
File "C:\Users\Administrator\Desktop\webscrapper\PdfDataExtraction.venv\Lib\site-packages\fpdf\fpdf.py", line 150, in wrapper
return fn(self, *args, **kwargs)
^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\Administrator\Desktop\webscrapper\PdfDataExtraction.venv\Lib\site-packages\fpdf\fpdf.py", line 963, in image
pos=name.rfind('.')
^^^^^^^^^^
AttributeError: '_io.BytesIO' object has no attribute 'rfind'
Assistant
The error you're encountering suggests that there's an issue with how the image is being added to the PDF using the fpdf library. Specifically, the image method in fpdf expects a filename for an image, but we're currently passing a BytesIO object instead.
Fixing the Code
To fix this issue, we need to save the image temporarily to a file before adding it to the PDF. Here’s how we can modify the relevant parts of the code to accommodate this:
Save the image to a temporary file before adding it to the PDF.
Clean up the temporary file after using it.
Here's the updated code for the create_pdf_a5 and create_pdf_a6 functions, including the necessary changes for handling image saving:
python
User
import os
import csv
import pandas as pd
from playwright.sync_api import sync_playwright
from PyPDF2 import PdfReader
from fpdf import FPDF
from PIL import Image
from io import BytesIO
import fitz
import tempfile # Import the tempfile module
def create_pdf_a6(input_pdf_path, output_4_per_page):
"""
Create a PDF with 4 pages per A6 sheet.
"""
print(f"Creating A6 format PDF from: {input_pdf_path}")
doc = fitz.open(input_pdf_path)
pdf_4_per_page = FPDF()
code
for i in range(0, len(doc), 4):
pdf_4_per_page.add_page()
for j in range(4):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
# Save to a temporary file
with tempfile.NamedTemporaryFile(delete=True, suffix=".png") as temp_file:
img.save(temp_file, format="PNG")
temp_file.seek(0) # Go to the beginning of the file
# Calculate position for A6
x_offset = (j % 2) * 105
y_offset = (j // 2) * 148.5
pdf_4_per_page.image(temp_file.name, x=x_offset, y=y_offset, w=105, h=148.5)
pdf_4_per_page.output(output_4_per_page)
print(f"A6 PDF saved at: {output_4_per_page}")
def create_pdf_a5(input_pdf_path, output_2_per_page_landscape):
"""
Create a PDF with 2 pages per A5 sheet in landscape orientation.
"""
print(f"Creating A5 format PDF from: {input_pdf_path}")
doc = fitz.open(input_pdf_path)
pdf_2_per_page_landscape = FPDF(orientation="L", unit="mm", format="A5")
code
Assistant
Your provided code looks good for generating A5 and A6 PDFs from the images extracted from patents. Below is the complete updated code with necessary parts included, ensuring that it combines all elements seamlessly. This includes the functions for scraping patent data, checking the number of PDF pages, and saving the final output.
import os
import csv
import pandas as pd
from playwright.sync_api import sync_playwright
TARGET_PAGE_URL = "https://iprsearch.ipindia.gov.in/PatentSearch/PatentSearch/eRegistrationReport"
PDF_DIRECTORY = "patent_pdfs1"
def scrape_patent_data(patent_number):
"""
Scrape patent data for a single patent number.
Fetches details like Legal Status, Patent Number, Application Number, Dates, etc.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
try:
os.makedirs(PDF_DIRECTORY, exist_ok=True)
print(f"Visiting the website for patent number: {patent_number}")
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000)
page.fill('input[name="PatentNumber"]', patent_number)
print("Please enter the CAPTCHA manually in the browser and submit the form.")
page.wait_for_url(TARGET_PAGE_URL, timeout=90000)
if page.locator("text=Sorry, we can't load the resource").is_visible():
print(f"Failed to load data for patent number {patent_number}: Sorry, we can't load the resource")
return {"Patent Number": patent_number, "Status": "Resource Not Loaded"}
print(f"Successfully loaded e-Register page for patent number {patent_number}.")
pdf_filename = f"{int(patent_number)}.pdf" # Convert to int to remove decimal
pdf_path = os.path.join(PDF_DIRECTORY, pdf_filename)
page.pdf(path=pdf_path)
print(f"PDF saved: {pdf_path}")
legal_status = safe_extract_text(page.locator('tr:has-text("Legal Status :") td:nth-child(2)'))
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)
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("Date of Grant") td:nth-child(3)'), default="N/A")
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)'))
date_of_patent = safe_extract_text(page.locator('tr:has-text("Date of Patent") td:nth-child(6)'))
date_of_grant = safe_extract_text(page.locator('tr:has-text("Date of Grant") td:nth-child(6)'))
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:
year = safe_extract_text(columns.nth(0)).replace('<sup>th</sup>', 'th')
renewal_amount = safe_extract_text(columns.nth(5))
renewal_date = safe_extract_text(columns.nth(7))
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 the fetched details
return {
'Patent Number': patent_number_text,
'Application Number': application_number,
'Legal Status': legal_status,
'Date Type': date_type,
'Date Value': date_value,
'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,
'Date of Patent': date_of_patent,
'Date of Grant': date_of_grant
}
except Exception as e:
print(f"Error during scraping for patent number {patent_number}: {e}")
return {"Patent Number": patent_number, "Status": "Error", "Error Message": str(e)}
finally:
browser.close()
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a Playwright locator.
"""
try:
return locator.inner_text().strip()
except Exception:
return default
def save_to_csv(data, filename):
"""
Append 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())
if not file_exists:
writer.writeheader()
writer.writerow(data)
if __name__ == "__main__":
input_file = r"C:\Users\Administrator\Downloads\Sample-Data-PatAnn.xlsx"
output_file = "data3.csv"
print("Reading patent numbers from Excel file...")
df = pd.read_excel(input_file)
if 'Patent No.' not in df.columns:
print("Column 'Patent No.' not found in Excel file.")
exit()
# Process each patent number
for idx, row in df.iterrows():
# Convert patent number to string, remove decimal part if present
patent_number = str(int(row['Patent No.'])) # Convert to int to remove .0 and back to str
print(f"\nProcessing patent number: {patent_number}")
scraped_data = scrape_patent_data(patent_number)
print(f"Saving extracted data for patent number {patent_number}...")
save_to_csv(scraped_data, output_file)
Changes Made:
In the main block, when processing the patent number from the DataFrame, we convert the patent number to an integer using int() to remove the decimal part. This integer is then converted back to a string when passed to scrape_patent_data.
The PDF filename is constructed with this cleaned patent number to prevent the .0 suffix.
This should resolve your issues with the patent numbers.
def scrape_patent_data(patent_number, pdf_path):
"""
Scrape patent data for a single patent number.
Fetches details like Legal Status, Patent Number, Application Number, Dates, etc.
Saves the page as a PDF.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
code
try:
os.makedirs(os.path.dirname(pdf_path), exist_ok=True)
print(f"Visiting the website for patent number: {patent_number}")
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000)
page.fill('input[name="PatentNumber"]', patent_number)
print("Please enter the CAPTCHA manually in the browser and submit the form.")
page.wait_for_url("https://iprsearch.ipindia.gov.in/PatentSearch/PatentSearch/eRegistrationReport", timeout=90000)
if page.locator("text=Sorry, we can't load the resource").is_visible():
print(f"Failed to load data for patent number {patent_number}: Sorry, we can't load the resource")
return None
print(f"Successfully loaded e-Register page for patent number {patent_number}.")
page.pdf(path=pdf_path, format="A4")
print(f"PDF saved: {pdf_path}")
return pdf_path # Return the path of the saved PDF
except Exception as e:
print(f"Error during scraping for patent number {patent_number}: {e}")
return None
finally:
browser.close()
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a Playwright locator.
"""
try:
return locator.inner_text().strip()
except Exception:
return default
def save_to_csv(data, filename):
"""
Append 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())
if not file_exists:
writer.writeheader()
writer.writerow(data)
if name == "main":
input_file = r"C:\Users\Administrator\Desktop\webscrapper\o1mini\Sample-Data-PatAnn.xlsx"
output_file = "data3.csv"
pdf_directory = "C:\Users\Administrator\Desktop\webscrapper\pdfs"
os.makedirs(pdf_directory, exist_ok=True)
code
print("Reading patent numbers from Excel file...")
df = pd.read_excel(input_file)
if 'Patent No.' not in df.columns:
print("Column 'Patent No.' not found in Excel file.")
exit()
pdf_files = []
for idx, row in df.iterrows():
patent_number = str(row['Patent No.'])
print(f"\nProcessing patent number: {patent_number}")
pdf_path = os.path.join(pdf_directory, f"{patent_number}.pdf")
scraped_data = scrape_patent_data(patent_number, pdf_path)
if scraped_data:
pdf_files.append(scraped_data)
print(f"Saving extracted data for patent number {patent_number}...")
save_to_csv({
'Patent Number': patent_number,
'PDF Path': scraped_data
}, output_file)
if pdf_files:
create_pdf_a6(pdf_directory + "\\", "C:\\Users\\Administrator\\Desktop\\webscrapper\\combined_A6.pdf")
create_pdf_a5(pdf_directory + "\\", "C:\\Users\\Administrator\\Desktop\\webscrapper\\combined_A5.pdf") in this where to see these last two files
import os
import csv
import pandas as pd
from playwright.sync_api import sync_playwright
from PyPDF2 import PdfReader
from fpdf import FPDF
from PIL import Image
from io import BytesIO
import fitz
def pixmap_to_image(pixmap):
img_data = pixmap.samples
img = Image.frombytes("RGB", [pixmap.width, pixmap.height], img_data)
return img
def create_pdf_a6(input_pdf_path, output_4_per_page):
"""
Create a PDF with 4 pages per A6 sheet.
"""
doc = fitz.open(input_pdf_path)
pdf_4_per_page = FPDF()
for i in range(0, len(doc), 4):
pdf_4_per_page.add_page()
for j in range(4):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
buffer = BytesIO()
img.save(buffer, format="PNG")
buffer.seek(0)
# Calculate position for A6
x_offset = (j % 2) * 105
y_offset = (j // 2) * 148.5
pdf_4_per_page.image(buffer, x=x_offset, y=y_offset, w=105, h=148.5)
pdf_4_per_page.output(output_4_per_page)
print(f"A6 PDF saved at: {output_4_per_page}")
def create_pdf_a5(input_pdf_path, output_2_per_page_landscape):
"""
Create a PDF with 2 pages per A5 sheet in landscape orientation.
"""
doc = fitz.open(input_pdf_path)
pdf_2_per_page_landscape = FPDF(orientation="L", unit="mm", format="A5")
for i in range(0, len(doc), 2):
pdf_2_per_page_landscape.add_page()
for j in range(2):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
buffer = BytesIO()
img.save(buffer, format="PNG")
buffer.seek(0)
# Calculate position for A5 landscape
x_offset = j * 148.5 # Half of A5 width
y_offset = 0
pdf_2_per_page_landscape.image(buffer, x=x_offset, y=y_offset, w=148.5, h=210)
pdf_2_per_page_landscape.output(output_2_per_page_landscape)
print(f"A5 Landscape PDF saved at: {output_2_per_page_landscape}")
def scrape_patent_data(patent_number, pdf_path):
"""
Scrape patent data for a single patent number.
Fetches details like Legal Status, Patent Number, Application Number, Dates, etc.
Saves the page as a PDF.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
try:
os.makedirs(os.path.dirname(pdf_path), exist_ok=True)
print(f"Visiting the website for patent number: {patent_number}")
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000)
page.fill('input[name="PatentNumber"]', patent_number)
print("Please enter the CAPTCHA manually in the browser and submit the form.")
page.wait_for_url("https://iprsearch.ipindia.gov.in/PatentSearch/PatentSearch/eRegistrationReport", timeout=90000)
if page.locator("text=Sorry, we can't load the resource").is_visible():
print(f"Failed to load data for patent number {patent_number}: Sorry, we can't load the resource")
return None
print(f"Successfully loaded e-Register page for patent number {patent_number}.")
page.pdf(path=pdf_path, format="A4")
print(f"PDF saved: {pdf_path}")
return pdf_path # Return the path of the saved PDF
except Exception as e:
print(f"Error during scraping for patent number {patent_number}: {e}")
return None
finally:
browser.close()
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a Playwright locator.
"""
try:
return locator.inner_text().strip()
except Exception:
return default
def save_to_csv(data, filename):
"""
Append 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())
if not file_exists:
writer.writeheader()
writer.writerow(data)
if __name__ == "__main__":
input_file = r"C:\Users\Administrator\Desktop\webscrapper\o1mini\Sample-Data-PatAnn.xlsx"
output_file = "data3.csv"
pdf_directory = "C:\\Users\\Administrator\\Desktop\\webscrapper\\pdfs"
os.makedirs(pdf_directory, exist_ok=True)
print("Reading patent numbers from Excel file...")
df = pd.read_excel(input_file)
if 'Patent No.' not in df.columns:
print("Column 'Patent No.' not found in Excel file.")
exit()
pdf_files = []
for idx, row in df.iterrows():
patent_number = str(row['Patent No.'])
print(f"\nProcessing patent number: {patent_number}")
pdf_path = os.path.join(pdf_directory, f"{patent_number}.pdf")
scraped_data = scrape_patent_data(patent_number, pdf_path)
if scraped_data:
pdf_files.append(scraped_data)
print(f"PDF for patent number {patent_number} saved at: {scraped_data}")
print(f"Saving extracted data for patent number {patent_number}...")
save_to_csv({
'Patent Number': patent_number,
'PDF Path': scraped_data
}, output_file)
print("All patents processed.")
print(f"Total number of PDFs created: {len(pdf_files)}")
if pdf_files:
print("Creating A6 combined PDF...")
create_pdf_a6(pdf_directory, "C:\\Users\\Administrator\\Desktop\\webscrapper\\combined_A6.pdf")
print("Creating A5 landscape combined PDF...")
create_pdf_a5(pdf_directory, "C:\\Users\\Administrator\\Desktop\\webscrapper\\combined_A5.pdf")
else:
print("No PDF files found for combining.")
Added Debug Statements
Before and after creating PDFs:
Print statements give you clear indications of what’s happening, especially before creating the PDFs combined.
If pdf_files is empty, it informs you upfront that no PDF files were found for combining.
PDF Generation Confirmation:
After each patent number is processed, a confirmation message is printed with the saved PDF path.
Total Number of PDFs:
After processing all patent numbers, it prints the total number of PDFs created, which gives you an idea of whether the scraping was successful or not.
Running the Code
After adding these debug statements, run the code again. Pay attention to the console output to see if any errors are reported or if it successfully processes and combines the PDF files.
Check the specified paths carefully to ensure the files are being saved correctly and that the program has access to these directories.
import os
import csv
import pandas as pd
from playwright.sync_api import sync_playwright
from PyPDF2 import PdfReader
from fpdf import FPDF
from PIL import Image
from io import BytesIO
import fitz
def pixmap_to_image(pixmap):
img_data = pixmap.samples
img = Image.frombytes("RGB", [pixmap.width, pixmap.height], img_data)
return img
def create_pdf_a6(input_pdf_path, output_4_per_page):
"""
Create a PDF with 4 pages per A6 sheet.
"""
print(f"Combining PDF files from: {input_pdf_path}")
doc = fitz.open(input_pdf_path)
pdf_4_per_page = FPDF()
for i in range(0, len(doc), 4):
pdf_4_per_page.add_page()
for j in range(4):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
buffer = BytesIO()
img.save(buffer, format="PNG")
buffer.seek(0)
# Calculate position for A6
x_offset = (j % 2) * 105
y_offset = (j // 2) * 148.5
pdf_4_per_page.image(buffer, x=x_offset, y=y_offset, w=105, h=148.5)
pdf_4_per_page.output(output_4_per_page)
print(f"A6 PDF saved at: {output_4_per_page}")
def create_pdf_a5(input_pdf_path, output_2_per_page_landscape):
"""
Create a PDF with 2 pages per A5 sheet in landscape orientation.
"""
print(f"Combining PDF files from: {input_pdf_path}")
doc = fitz.open(input_pdf_path)
pdf_2_per_page_landscape = FPDF(orientation="L", unit="mm", format="A5")
for i in range(0, len(doc), 2):
pdf_2_per_page_landscape.add_page()
for j in range(2):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
buffer = BytesIO()
img.save(buffer, format="PNG")
buffer.seek(0)
# Calculate position for A5 landscape
x_offset = j * 148.5 # Half of A5 width
y_offset = 0
pdf_2_per_page_landscape.image(buffer, x=x_offset, y=y_offset, w=148.5, h=210)
pdf_2_per_page_landscape.output(output_2_per_page_landscape)
print(f"A5 Landscape PDF saved at: {output_2_per_page_landscape}")
def scrape_patent_data(patent_number, pdf_path):
"""
Scrape patent data for a single patent number.
Fetches details like Legal Status, Patent Number, Application Number, Dates, etc.
Saves the page as a PDF.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
try:
os.makedirs(os.path.dirname(pdf_path), exist_ok=True)
print(f"Visiting the website for patent number: {patent_number}")
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000)
page.fill('input[name="PatentNumber"]', patent_number)
print("Please enter the CAPTCHA manually in the browser and submit the form.")
page.wait_for_url("https://iprsearch.ipindia.gov.in/PatentSearch/PatentSearch/eRegistrationReport", timeout=90000)
if page.locator("text=Sorry, we can't load the resource").is_visible():
print(f"Failed to load data for patent number {patent_number}: Sorry, we can't load the resource")
return None
print(f"Successfully loaded e-Register page for patent number {patent_number}.")
page.pdf(path=pdf_path, format="A4")
print(f"PDF saved: {pdf_path}")
return pdf_path # Return the path of the saved PDF
except Exception as e:
print(f"Error during scraping for patent number {patent_number}: {e}")
return None
finally:
browser.close()
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a Playwright locator.
"""
try:
return locator.inner_text().strip()
except Exception:
return default
def save_to_csv(data, filename):
"""
Append 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())
if not file_exists:
writer.writeheader()
writer.writerow(data)
if __name__ == "__main__":
input_file = r"C:\Users\Administrator\Desktop\webscrapper\o1mini\Sample-Data-PatAnn.xlsx"
output_file = "data3.csv"
pdf_directory = "C:\\Users\\Administrator\\Desktop\\webscrapper\\pdfs"
os.makedirs(pdf_directory, exist_ok=True)
print("Reading patent numbers from Excel file...")
df = pd.read_excel(input_file)
if 'Patent No.' not in df.columns:
print("Column 'Patent No.' not found in Excel file.")
exit()
pdf_files = []
for idx, row in df.iterrows():
patent_number = str(row['Patent No.'])
print(f"\nProcessing patent number: {patent_number}")
pdf_path = os.path.join(pdf_directory, f"{patent_number}.pdf")
scraped_data = scrape_patent_data(patent_number, pdf_path)
if scraped_data:
pdf_files.append(scraped_data)
print(f"PDF for patent number {patent_number} saved at: {scraped_data}")
print(f"Saving extracted data for patent number {patent_number}...")
save_to_csv({
'Patent Number': patent_number,
'PDF Path': scraped_data
}, output_file)
print("All patents processed.")
print(f"Total number of PDFs created: {len(pdf_files)}")
if pdf_files:
print("Creating A6 combined PDF...")
create_pdf_a6(pdf_directory, "C:\\Users\\Administrator\\Desktop\\webscrapper\\combined_A6.pdf")
print("Creating A5 landscape combined PDF...")
create_pdf_a5(pdf_directory, "C:\\Users\\Administrator\\Desktop\\webscrapper\\combined_A5.pdf")
else:
print("No PDF files found for combining.")
print("Script execution completed.")
Key Changes:
Debug Statements in Combining Functions:
Added print statements to indicate the start of the combining process for both create_pdf_a6 and create_pdf_a5 functions.
Checking PDF Creation:
Checks the number of PDFs created and confirms whether any PDFs are found for combining.
Final Execution Confirmation:
A final print statement to indicate that the script execution is completed successfully.
Running the Script
Execute the Script: Run the script and keep an eye on the console output. You should see debug statements that track the process of creating individual PDFs and combining them.
Check Output Location: Ensure that you check the specified output folder (C:\Users\Administrator\Desktop\webscrapper\) for the combined PDF files after running the script.
This will give you a clear idea of where the process is succeeding and if any part of it fails, allowing you to catch errors that could previously have gone unnoticed.
Changes Made:
Function to Get Page Count:
A new function called get_pdf_page_count(pdf_path) is created to count the number of pages in a PDF file.
Logic to Determine A5 or A6:
After scraping and saving the patent PDF, the code checks the number of pages.
If the number of pages is 1 or 2, it calls create_pdf_a5() to save the PDF in A5 format.
If there are more than 2 pages, it calls create_pdf_a6() to save it in A6 format.
Modified Output Paths:
The paths for the newly saved A5 and A6 PDFs are constructed dynamically based on the patent number.
Testing the Updated Code
Run the updated script, and it should save each patent’s PDF based on the number of pages in either A5 or A6 format as specified. Make sure to check the specified folder for the newly created PDF files after execution.
Important Notes
Ensure the required libraries (like PyPDF2, PIL, and fpdf) are installed in your Python environment.
The PDF generation methods from the earlier code should remain untouched for creating A5 and A6 PDFs as they handle the layout correctly.
import os
import csv
import pandas as pd
from playwright.sync_api import sync_playwright
from PyPDF2 import PdfReader
from fpdf import FPDF
from PIL import Image
from io import BytesIO
import fitz
def pixmap_to_image(pixmap):
img_data = pixmap.samples
img = Image.frombytes("RGB", [pixmap.width, pixmap.height], img_data)
return img
def create_pdf_a6(input_pdf_path, output_4_per_page):
"""
Create a PDF with 4 pages per A6 sheet.
"""
print(f"Creating A6 format PDF from: {input_pdf_path}")
doc = fitz.open(input_pdf_path)
pdf_4_per_page = FPDF()
for i in range(0, len(doc), 4):
pdf_4_per_page.add_page()
for j in range(4):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
buffer = BytesIO()
img.save(buffer, format="PNG")
buffer.seek(0)
# Calculate position for A6
x_offset = (j % 2) * 105
y_offset = (j // 2) * 148.5
pdf_4_per_page.image(buffer, x=x_offset, y=y_offset, w=105, h=148.5)
pdf_4_per_page.output(output_4_per_page)
print(f"A6 PDF saved at: {output_4_per_page}")
def create_pdf_a5(input_pdf_path, output_2_per_page_landscape):
"""
Create a PDF with 2 pages per A5 sheet in landscape orientation.
"""
print(f"Creating A5 format PDF from: {input_pdf_path}")
doc = fitz.open(input_pdf_path)
pdf_2_per_page_landscape = FPDF(orientation="L", unit="mm", format="A5")
for i in range(0, len(doc), 2):
pdf_2_per_page_landscape.add_page()
for j in range(2):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
buffer = BytesIO()
img.save(buffer, format="PNG")
buffer.seek(0)
# Calculate position for A5 landscape
x_offset = j * 148.5 # Half of A5 width
y_offset = 0
pdf_2_per_page_landscape.image(buffer, x=x_offset, y=y_offset, w=148.5, h=210)
pdf_2_per_page_landscape.output(output_2_per_page_landscape)
print(f"A5 Landscape PDF saved at: {output_2_per_page_landscape}")
def scrape_patent_data(patent_number, pdf_path):
"""
Scrape patent data for a single patent number.
Fetches details like Legal Status, Patent Number, Application Number, Dates, etc.
Saves the page as a PDF.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
try:
os.makedirs(os.path.dirname(pdf_path), exist_ok=True)
print(f"Visiting the website for patent number: {patent_number}")
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000)
page.fill('input[name="PatentNumber"]', patent_number)
print("Please enter the CAPTCHA manually in the browser and submit the form.")
page.wait_for_url("https://iprsearch.ipindia.gov.in/PatentSearch/PatentSearch/eRegistrationReport", timeout=90000)
if page.locator("text=Sorry, we can't load the resource").is_visible():
print(f"Failed to load data for patent number {patent_number}: Sorry, we can't load the resource")
return None
print(f"Successfully loaded e-Register page for patent number {patent_number}.")
page.pdf(path=pdf_path, format="A4")
print(f"PDF saved: {pdf_path}")
return pdf_path # Return the path of the saved PDF
except Exception as e:
print(f"Error during scraping for patent number {patent_number}: {e}")
return None
finally:
browser.close()
def get_pdf_page_count(pdf_path):
"""
Get the number of pages in a PDF file.
"""
with open(pdf_path, "rb") as f:
reader = PdfReader(f)
return len(reader.pages)
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a Playwright locator.
"""
try:
return locator.inner_text().strip()
except Exception:
return default
def save_to_csv(data, filename):
"""
Append 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())
if not file_exists:
writer.writeheader()
writer.writerow(data)
if __name__ == "__main__":
input_file = r"C:\Users\Administrator\Desktop\webscrapper\o1mini\Sample-Data-PatAnn.xlsx"
output_file = "data3.csv"
pdf_directory = "C:\\Users\\Administrator\\Desktop\\webscrapper\\pdfs"
os.makedirs(pdf_directory, exist_ok=True)
print("Reading patent numbers from Excel file...")
df = pd.read_excel(input_file)
if 'Patent No.' not in df.columns:
print("Column 'Patent No.' not found in Excel file.")
exit()
pdf_files = []
for idx, row in df.iterrows():
patent_number = str(row['Patent No.'])
print(f"\nProcessing patent number: {patent_number}")
pdf_path = os.path.join(pdf_directory, f"{patent_number}.pdf")
scraped_data = scrape_patent_data(patent_number, pdf_path)
if scraped_data:
num_pages = get_pdf_page_count(scraped_data) # Get the number of pages in the created PDF
print(f"Patent number {patent_number} PDF has {num_pages} page(s).")
if num_pages <= 2:
# Save as A5
print(f"Saving {patent_number} PDF to A5 format.")
create_pdf_a5(pdf_path, os.path.join(pdf_directory, f"{patent_number}_A5.pdf"))
else:
# Save as A6
print(f"Saving {patent_number} PDF to A6 format.")
create_pdf_a6(pdf_path, os.path.join(pdf_directory, f"{patent_number}_A6.pdf"))
pdf_files.append(scraped_data)
print(f"PDF for patent number {patent_number} saved at: {scraped_data}")
print(f"Saving extracted data for patent number {patent_number}...")
save_to_csv({
'Patent Number': patent_number,
'PDF Path': scraped_data
}, output_file)
print("All patents processed.")
print(f"Total number of PDFs created: {len(pdf_files)}")
print("Script execution completed.")
Overview of Key Features:
PDF Creation: It checks the number of pages in the generated PDF and saves it in either A5 or A6 format.
Scraping Patent Data: The scrape_patent_data function collects data from the specified website and saves it as a PDF.
Page Count Function: The get_pdf_page_count function is used to determine how many pages the generated PDF has.
Dynamic Output Naming: For each patent, the generated PDF files are saved with either _A5.pdf or _A6.pdf suffixes based on the page count.
Installation Requirements
Make sure you have the necessary packages installed before running the code. You can install them using pip if you haven’t already:
Update the input_file variable with the path to your Excel file containing patent numbers.
Execute the script in your Python environment.
Check C:\Users\Administrator\Desktop\webscrapper\pdfs for the generated A5 and A6 PDFs.
This code will meet your requirement of saving each patent's PDF based on its page count efficiently.
import os
import csv
import pandas as pd
from playwright.sync_api import sync_playwright
from PyPDF2 import PdfReader
from fpdf import FPDF
from PIL import Image
from io import BytesIO
import fitz
import tempfile # Import the tempfile module
def pixmap_to_image(pixmap):
img_data = pixmap.samples
img = Image.frombytes("RGB", [pixmap.width, pixmap.height], img_data)
return img
def create_pdf_a6(input_pdf_path, output_4_per_page):
"""
Create a PDF with 4 pages per A6 sheet.
"""
print(f"Creating A6 format PDF from: {input_pdf_path}")
doc = fitz.open(input_pdf_path)
pdf_4_per_page = FPDF()
for i in range(0, len(doc), 4):
pdf_4_per_page.add_page()
for j in range(4):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
# Save to a temporary file
with tempfile.NamedTemporaryFile(delete=True, suffix=".png") as temp_file:
img.save(temp_file, format="PNG")
temp_file.seek(0) # Go to the beginning of the file
# Calculate position for A6
x_offset = (j % 2) * 105
y_offset = (j // 2) * 148.5
pdf_4_per_page.image(temp_file.name, x=x_offset, y=y_offset, w=105, h=148.5)
pdf_4_per_page.output(output_4_per_page)
print(f"A6 PDF saved at: {output_4_per_page}")
def create_pdf_a5(input_pdf_path, output_2_per_page_landscape):
"""
Create a PDF with 2 pages per A5 sheet in landscape orientation.
"""
print(f"Creating A5 format PDF from: {input_pdf_path}")
doc = fitz.open(input_pdf_path)
pdf_2_per_page_landscape = FPDF(orientation="L", unit="mm", format="A5")
for i in range(0, len(doc), 2):
pdf_2_per_page_landscape.add_page()
for j in range(2):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
# Save to a temporary file
with tempfile.NamedTemporaryFile(delete=True, suffix=".png") as temp_file:
img.save(temp_file, format="PNG")
temp_file.seek(0) # Go to the beginning of the file
# Calculate position for A5 landscape
x_offset = j * 148.5 # Half of A5 width
y_offset = 0
pdf_2_per_page_landscape.image(temp_file.name, x=x_offset, y=y_offset, w=148.5, h=210)
pdf_2_per_page_landscape.output(output_2_per_page_landscape)
print(f"A5 Landscape PDF saved at: {output_2_per_page_landscape}")
# (The rest of the code remains unchanged)
Key Changes:
Using tempfile.NamedTemporaryFile:
The image is saved to a temporary PNG file, which is automatically deleted after being closed.
This allows you to provide a filename to the pdf_2_per_page_landscape.image() method, fixing the AttributeError.
Seeking Back to the Start:
After saving the image to the temporary file, we seek back to the beginning to ensure that it can be read properly by the fpdf library.
Running the Updated Code
Ensure you have the necessary packages installed (Pillow, fpdf, PyPDF2, fitz, playwright, and pandas).
Update the relevant paths in the code as needed and run it again.
With these changes, the script should now handle the creation of A5 and A6 PDFs correctly without encountering any exceptions related to handling image data.
for i in range(0, len(doc), 2):
pdf_2_per_page_landscape.add_page()
for j in range(2):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
# Save to a temporary file
with tempfile.NamedTemporaryFile(delete=True, suffix=".png") as temp_file:
img.save(temp_file, format="PNG")
temp_file.seek(0) # Go to the beginning of the file
# Calculate position for A5 landscape
x_offset = j * 148.5 # Half of A5 width
y_offset = 0
pdf_2_per_page_landscape.image(temp_file.name, x=x_offset, y=y_offset, w=148.5, h=210)
pdf_2_per_page_landscape.output(output_2_per_page_landscape)
print(f"A5 Landscape PDF saved at: {output_2_per_page_landscape}")
(The rest of the code remains unchanged)
import os
import csv
import pandas as pd
from playwright.sync_api import sync_playwright
from PyPDF2 import PdfReader
from fpdf import FPDF
from PIL import Image
from io import BytesIO
import fitz
import tempfile # Import the tempfile module
def pixmap_to_image(pixmap):
img_data = pixmap.samples
img = Image.frombytes("RGB", [pixmap.width, pixmap.height], img_data)
return img
def create_pdf_a6(input_pdf_path, output_4_per_page):
"""
Create a PDF with 4 pages per A6 sheet.
"""
print(f"Creating A6 format PDF from: {input_pdf_path}")
doc = fitz.open(input_pdf_path)
pdf_4_per_page = FPDF()
for i in range(0, len(doc), 4):
pdf_4_per_page.add_page()
for j in range(4):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
# Save to a temporary file
with tempfile.NamedTemporaryFile(delete=True, suffix=".png") as temp_file:
img.save(temp_file, format="PNG")
temp_file.seek(0) # Go to the beginning of the file
# Calculate position for A6
x_offset = (j % 2) * 105
y_offset = (j // 2) * 148.5
pdf_4_per_page.image(temp_file.name, x=x_offset, y=y_offset, w=105, h=148.5)
pdf_4_per_page.output(output_4_per_page)
print(f"A6 PDF saved at: {output_4_per_page}")
def create_pdf_a5(input_pdf_path, output_2_per_page_landscape):
"""
Create a PDF with 2 pages per A5 sheet in landscape orientation.
"""
print(f"Creating A5 format PDF from: {input_pdf_path}")
doc = fitz.open(input_pdf_path)
pdf_2_per_page_landscape = FPDF(orientation="L", unit="mm", format="A5")
for i in range(0, len(doc), 2):
pdf_2_per_page_landscape.add_page()
for j in range(2):
page_idx = i + j
if page_idx < len(doc):
pixmap = doc.load_page(page_idx).get_pixmap()
img = pixmap_to_image(pixmap)
# Save to a temporary file
with tempfile.NamedTemporaryFile(delete=True, suffix=".png") as temp_file:
img.save(temp_file, format="PNG")
temp_file.seek(0) # Go to the beginning of the file
# Calculate position for A5 landscape
x_offset = j * 148.5 # Half of A5 width
y_offset = 0
pdf_2_per_page_landscape.image(temp_file.name, x=x_offset, y=y_offset, w=148.5, h=210)
pdf_2_per_page_landscape.output(output_2_per_page_landscape)
print(f"A5 Landscape PDF saved at: {output_2_per_page_landscape}")
def scrape_patent_data(patent_number, pdf_path):
"""
Scrape patent data for a single patent number.
Fetches details like Legal Status, Patent Number, Application Number, Dates, etc.
Saves the page as a PDF.
"""
with sync_playwright() as p:
browser = p.chromium.launch(headless=False)
page = browser.new_page()
try:
os.makedirs(os.path.dirname(pdf_path), exist_ok=True)
print(f"Visiting the website for patent number: {patent_number}")
page.goto("https://iprsearch.ipindia.gov.in/PublicSearch/PublicationSearch/Eregister",
wait_until="domcontentloaded", timeout=60000)
page.wait_for_selector('input[name="PatentNumber"]', timeout=60000)
page.fill('input[name="PatentNumber"]', patent_number)
print("Please enter the CAPTCHA manually in the browser and submit the form.")
page.wait_for_url("https://iprsearch.ipindia.gov.in/PatentSearch/PatentSearch/eRegistrationReport", timeout=90000)
if page.locator("text=Sorry, we can't load the resource").is_visible():
print(f"Failed to load data for patent number {patent_number}: Sorry, we can't load the resource")
return None
print(f"Successfully loaded e-Register page for patent number {patent_number}.")
page.pdf(path=pdf_path, format="A4")
print(f"PDF saved: {pdf_path}")
return pdf_path # Return the path of the saved PDF
except Exception as e:
print(f"Error during scraping for patent number {patent_number}: {e}")
return None
finally:
browser.close()
def get_pdf_page_count(pdf_path):
"""
Get the number of pages in a PDF file.
"""
with open(pdf_path, "rb") as f:
reader = PdfReader(f)
return len(reader.pages)
def safe_extract_text(locator, default='N/A'):
"""
Safely extract text from a Playwright locator.
"""
try:
return locator.inner_text().strip()
except Exception:
return default
def save_to_csv(data, filename):
"""
Append 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())
if not file_exists:
writer.writeheader()
writer.writerow(data)
if __name__ == "__main__":
input_file = r"C:\Users\Administrator\Desktop\webscrapper\o1mini\Sample-Data-PatAnn.xlsx"
output_file = "data3.csv"
pdf_directory = "C:\\Users\\Administrator\\Desktop\\webscrapper\\pdfs"
os.makedirs(pdf_directory, exist_ok=True)
print("Reading patent numbers from Excel file...")
df = pd.read_excel(input_file)
if 'Patent No.' not in df.columns:
print("Column 'Patent No.' not found in Excel file.")
exit()
pdf_files = []
for idx, row in df.iterrows():
patent_number = str(row['Patent No.'])
print(f"\nProcessing patent number: {patent_number}")
pdf_path = os.path.join(pdf_directory, f"{patent_number}.pdf")
scraped_data = scrape_patent_data(patent_number, pdf_path)
if scraped_data:
num_pages = get_pdf_page_count(scraped_data) # Get the number of pages in the created PDF
print(f"Patent number {patent_number} PDF has {num_pages} page(s).")
if num_pages <= 2:
# Save as A5
print(f"Saving {patent_number} PDF to A5 format.")
create_pdf_a5(pdf_path, os.path.join(pdf_directory, f"{patent_number}_A5.pdf"))
else:
# Save as A6
print(f"Saving {patent_number} PDF to A6 format.")
create_pdf_a6(pdf_path, os.path.join(pdf_directory, f"{patent_number}_A6.pdf"))
pdf_files.append(scraped_data)
print(f"PDF for patent number {patent_number} saved at: {scraped_data}")
print(f"Saving extracted data for patent number {patent_number}...")
save_to_csv({
'Patent Number': patent_number,
'PDF Path': scraped_data
}, output_file)
print("All patents processed.")
print(f"Total number of PDFs created: {len(pdf_files)}")
print("Script execution completed.")
How It Works
Import Libraries: All the necessary libraries are imported.
Image Conversion and PDF Creation:
The pixmap_to_image function converts page images into a format usable by FPDF.
The create_pdf_a5 and create_pdf_a6 functions manage the A5 and A6 formatting, creating temporary files for images.
Scraping and Saving:
The scrape_patent_data function fetches data and generates the initial PDF.
After the PDF is generated, the script checks the number of pages using get_pdf_page_count.
Based on the page count, it saves the PDF in either A5 or A6 format accordingly.
CSV Saving: The save_to_csv function appends extracted patent data to a CSV file.
Running the Code
Make sure to:
Update the input_file path as needed.
Have all necessary packages installed.
Provide valid patent numbers in the Excel file.
After executing the script, check for generated PDFs in the specified output folder. You should find A5 PDFs for those with 1-2 pages and A6 PDFs for those with more than 2 pages.