Skip to content

fetch: add user_agent to the urllib2 request. #22

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions opengraph/opengraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ class OpenGraph(dict):

required_attrs = ['title', 'type', 'image', 'url', 'description']

def __init__(self, url=None, html=None, scrape=False, **kwargs):
def __init__(self, url=None, html=None, scrape=False, user_agent=None, **kwargs):
# If scrape == True, then will try to fetch missing attribtues
# from the page's body

Expand All @@ -33,7 +33,7 @@ def __init__(self, url=None, html=None, scrape=False, **kwargs):
dict.__init__(self)

if url is not None:
self.fetch(url)
self.fetch(url, user_agent)

if html is not None:
self.parser(html)
Expand All @@ -44,10 +44,13 @@ def __setattr__(self, name, val):
def __getattr__(self, name):
return self[name]

def fetch(self, url):
def fetch(self, url, user_agent):
"""
"""
raw = urllib2.urlopen(url)
req = urllib2.Request(url)
if user_agent:
req.add_header('User-agent', user_agent)
raw = urllib2.urlopen(req)
html = raw.read()
return self.parser(html)

Expand Down