Skip to content

Instantly share code, notes, and snippets.

@ahmedshahriar
Created February 10, 2021 19:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ahmedshahriar/3de09de6a37a21edeb3c83cbc3dbcc57 to your computer and use it in GitHub Desktop.
Save ahmedshahriar/3de09de6a37a21edeb3c83cbc3dbcc57 to your computer and use it in GitHub Desktop.
Faster HTTP Requests with Session
"""
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