MEET PATEL
MEET PATEL

Reputation: 1

How we can use multithreading for sending a POST request to URL with headers in python?

import requests
#Making session
m1 = requests.Session()
#URL And DAta
url = 'https://www.w3schools.com/python/demopage.php'
myobj = {'somekey': 'somevalue'}
#Creating connection an sending request
x = m1.post(url, data = myobj)
#printing response

print(x)

Upvotes: 0

Views: 170

Answers (1)

wind
wind

Reputation: 2441

You can do it like this:

import threading
import requests

list_of_links = [
    # All your links and headers here in tuples
]

threads = []

all_html = {
    # This will be a dictionary of the links as key and the Response object of the links as values
}


def get_html(link, headers):
    r = requests.post(link, data=headers)
    all_html[link] = r


for link, header in list_of_links:
    thread = threading.Thread(target=get_html, args=(link, header))
    thread.start()
    threads.append(thread)
   
for t in threads:
    t.join()
    
print(all_html)

print("DONE")

Upvotes: 1

Related Questions