Created
February 10, 2021 19:42
-
-
Save ahmedshahriar/3de09de6a37a21edeb3c83cbc3dbcc57 to your computer and use it in GitHub Desktop.
Faster HTTP Requests with Session
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
requests with session gives faster results | |
the below code demonstrates a comparison in speed between requests with session vs requests not with session | |
""" | |
import requests | |
import datetime | |
from bs4 import BeautifulSoup | |
def scrape_no_session(x): | |
url = f"https://scrapethissite.com/pages/forms/?page_num={x}" | |
r = requests.get(url) | |
soup = BeautifulSoup(r.text,'html.parser') | |
print(soup.title.text) | |
def scrape_with_session(x): | |
url = f"https://scrapethissite.com/pages/forms/?page_num={x}" | |
s = requests.Session() | |
r = s.get(url) | |
soup = BeautifulSoup(r.text,'html.parser') | |
print(soup.title.text) | |
start = datetime.datetime.now() | |
for x in range(1,24): | |
scrape_no_session(x) | |
print(f"duration : {datetime.datetime.now()-start}") | |
start = datetime.datetime.now() | |
for x in range(1,24): | |
scrape_with_session(x) | |
print(f"duration : {datetime.datetime.now()-start}") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment