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_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\Desktop\webscrapper\o1mini\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():
        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)



   take the refernce from this code ..we have to do the same but now somthing is diffrent ...path: https://ipronline.ipindia.gov.in/epatentfiling/goForLogin/doLogin

Intellectual Property India

 
Login > Renewal of Patent (button) > enter patent No. > enter a in  > capture first line on the page in excel

Login --- REdirected to --> https://ipronline.ipindia.gov.in/epatentfiling/OnlineFiling/OnlineFormFiling  now for all the patent no of single excel remain on this page then caluculate 

   <tr>
                                                <td style="border-bottom: solid 0.5px #353c61" align="left">
                                                    <a id="ctl00_ctl00_ContentPlaceHolder1_FilingPane_content_LinkRenewalOfPatent" title="Renewal of Patent" class="LinkButtonStyle" href="javascript:__doPostBack(&#39;ctl00$ctl00$ContentPlaceHolder1$FilingPane_content$LinkRenewalOfPatent&#39;,&#39;&#39;)">Renewal of Patent</a><br />
                                                </td>
                                                <tr>  

<tr id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder2_RowApp">
		<td align="right" style="width: 168px">
                            <span id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder2_LblAppNum" class="FieldLabel">Patent Number</span>
                        </td>
		<td align="left" style="width: 382px">
                            <input name="ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder2$txtApplicationNumber" type="text" autocomplete="off" id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder2_txtApplicationNumber" class="txtBoxStyle" style="width:161px;" />
                            <span id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder2_RequiredFieldValidator1" style="display:none;">Please Enter Value</span>
                              
                        </td>
	</tr>
	
                    <tr>
                        <td align="right" style="width: 168px">&nbsp;
                        </td>
                        <td align="left" style="width: 382px">
                            <span id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder2_lblMsg" style="color:Red;font-family:Book Antiqua;font-size:Medium;font-weight:bold;"></span>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" style="width: 168px">&nbsp;
                        </td>
                        <td align="left" style="width: 382px">
                            <a id="ctl00_ctl00_ContentPlaceHolder1_ContentPlaceHolder2_LnkSubmit" class="MenuButtonStyle" href="javascript:WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions(&quot;ctl00$ctl00$ContentPlaceHolder1$ContentPlaceHolder2$LnkSubmit&quot;, &quot;&quot;, true, &quot;&quot;, &quot;&quot;, false, true))">Submit</a>
                        </td>
                    </tr>     fill this patent no from excel prsss submit

WAIT FOR SOME TIME FOR USER TO ENTER A IN A END THEN WHEN the page https://ipronline.ipindia.gov.in/epatentfiling/FORM30/frmRENEWAL-OF-PATENTS.aspx   loads  thne capture the line after Renewal against patent number: 363654 have been paid for Years 3,4,5,6,7,8,9 
means 363654 have been paid fir yrs 3,4,,56,7,8,9, in csv with patent number