Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set session cookie while extracting contents from URLs using beautiful soup?

Consider the code:

from bs4 import BeautifulSoup
from urllib.request import urlopen
content = urlopen('https://example.net/users/101')
soup = BeautifulSoup(content)
divTag = soup.find_all("div", {"class":"classname"})
print(divTag)
for tag in divTag:
   ulTags = tag.find_all("ul", {"class":"classname"})
   for tag in ulTags:
       aTags = tag.find_all("li")
       for tag in aTags:
           name = tag.find('a')['href']
           print(name)

If i use,

content = open("try.html","r")

I get the required output.

Here, example.net can be accessed only after entering username & password. The above code does not print anything although the parsing is done correctly.How to add the session cookie value to this code ?

like image 361
shahnaz shariff Avatar asked May 26 '15 05:05

shahnaz shariff


1 Answers

Have you tried requests ?

It is possible to persist cookies across a session.

import requests
s = requests.Session()
s.post('https://example.net/users/101', data = {'username' : 'sup', 'password' : 'pass'})
r = s.get("https://example.net/users/101")
soup = BeautifulSoup(r.text)

more about requests.Session()

http://docs.python-requests.org/en/latest/user/advanced/

like image 119
HaseebR7 Avatar answered Oct 21 '22 01:10

HaseebR7