Skip to content
This repository was archived by the owner on May 30, 2020. It is now read-only.

Adding support for Custom HTML parser #10

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
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
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -58,3 +58,6 @@ target/

# SublimeText project/workspace
*.sublime*

# Pycharm
.idea
15 changes: 6 additions & 9 deletions opengraph/opengraph.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,19 @@ class OpenGraph(object):
useragent = None
__data__ = {}

def __init__(self, url=None, html=None, useragent=None):
def __init__(self, url=None, html=None, useragent=None, html_parser='html.parser'):
if useragent:
self.useragent = useragent
content = html or self._fetch(url)
self._parse(content)
self._parse(content, html_parser)

def __contains__(self, item):
return item in self.__data__

def __getattr__(self, name):
if name in self.__data__:
return self.__data__[name]
raise AttributeError(
'Open Graph object has no attribute "{}"'.format(name))
raise AttributeError('Open Graph object has no attribute "{}"'.format(name))

def __repr__(self):
return self.__data__.__str__()
Expand All @@ -35,14 +34,12 @@ def __str__(self):
def _fetch(self, url):
headers = {}
if self.useragent:
headers = {
'user-agent': self.useragent
}
headers = {'user-agent': self.useragent}
response = requests.get(url, headers=headers)
return response.text

def _parse(self, html):
doc = BeautifulSoup(html)
def _parse(self, html, html_parser):
doc = BeautifulSoup(html, html_parser)
ogs = doc.html.head.findAll(property=re.compile(r'^og'))

for og in ogs:
Expand Down