Search code examples
pythonpython-requestsrequest

How can pass the parameter value form input.txt file using python?


I want the pass the dynamic values in params from input.txt file?

input.txt file:-

term=ditech process solutions,country=IN,action=get_search_companies

For this code:-

import requests
from bs4 import BeautifulSoup


def read_params(file_path):
    params = {}
    with open(file_path, 'r') as file:
        for line in file:
            key, value = line.strip().split('=')
            params[key] = value
    return params


api_url = "https://lei-registrations.in/wp/wp-admin/admin-ajax.php"

input_file_path = "input.txt"

params = read_params(input_file_path)

# manual using params
# params = {
#     "term": "ditech process solutions",  # <-- search term
#     "country": "IN",
#     "action": "get_search_companies",
# }

headers = {
    "User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:122.0) Gecko/20100101 Firefox/122.0"
}

data = requests.get(api_url, params=params, headers=headers).json()

if data["success"]:
    soup = BeautifulSoup(data["data"], "html.parser")
    for r in soup.select(".searchResults_title"):
        name = r.select_one(".searchResults_name").text
        number = r.select_one(".searchResults_number").text

        print(f"{name:<50} {number}")

Solution

  • Text file:

    {
        "term": "ditech process solutions",
        "country": "IN",
        "action": "get_search_companies",
    }
    

    Code to read file:

    import json
    
    input_file_path = "input.txt"
    
    with open(input_file_path) as json_data:
        params = json.load(json_data)
    

    Documentation: