Skip to content

Added to_dict #196

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 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
6 changes: 6 additions & 0 deletions TESTING.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
# Run the following to run unit tests
`python -m unittest`


# Integration Tests
`python ./test/scrape_person.py`
20 changes: 18 additions & 2 deletions linkedin_scraper/person.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,24 @@
import requests
from typing import Dict, Any

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException
from .objects import Experience, Education, Scraper, Interest, Accomplishment, Contact
from .utils import to_dict
import os
from linkedin_scraper import selectors


class Person(Scraper):

__TOP_CARD = "pv-top-card"
__WAIT_FOR_ELEMENT_TIMEOUT = 5


linkedin_url: str
name: str

def __init__(
self,
linkedin_url=None,
Expand Down Expand Up @@ -392,3 +397,14 @@ def __repr__(self):
acc=self.accomplishments,
conn=self.contacts,
)

def to_dict(self) -> Dict[str, Any]:
return to_dict({
'name': self.name,
'about': self.about,
'experiences': self.experiences,
'educations': self.educations,
'interests': self.interests,
'accomplishments': self.accomplishments,
'contacts': self.contacts,
})
40 changes: 40 additions & 0 deletions linkedin_scraper/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""
Utilities
"""
import io
from typing import Dict, Any, List
from dataclasses import is_dataclass, asdict


def custom_asdict(obj):
# Custom asdict function that excludes _io.BufferedWriter objects
obj_dict = {}
for field in obj.__dataclass_fields__.values():
value = getattr(obj, field.name)
if not isinstance(value, io.BufferedWriter):
obj_dict[field.name] = to_dict(value)
return obj_dict

def to_dict(obj) -> Dict[str, Any]:
if is_dataclass(obj):
# If the object is a data class, use asdict to convert it to a dictionary
return to_dict(custom_asdict(obj))

if isinstance(obj, (int, str, bool, float)):
# If the object is a basic type, return it as is
return obj

if isinstance(obj, list):
# If the object is a list, recursively call to_dict on its elements
return [to_dict(item) for item in obj]

if isinstance(obj, dict):
# If the object is a dictionary, recursively call to_dict on its values
return {key: to_dict(value) for key, value in obj.items() if not key.startswith('_')}

if hasattr(obj, '__dict__'):
# If the object has a __dict__ attribute, recursively call to_dict on its attributes
return {key: to_dict(value) for key, value in obj.__dict__.items() if not key.startswith('_')}

# If none of the above conditions match, return None (or handle as needed)
return None
6 changes: 6 additions & 0 deletions test/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import os
import sys

current_dir = os.path.dirname(os.path.abspath(__file__))
root_dir = os.path.dirname(current_dir)
sys.path.append(root_dir) # Add the parent directory to sys.path
5 changes: 5 additions & 0 deletions test/scrape_person.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Integration test
import __init__
from linkedin_scraper import Person

rick_fox = Person("https://www.linkedin.com/in/rifox?trk=pub-pbmap")
rick_fox.to_dict()
iggy = Person("https://www.linkedin.com/in/andre-iguodala-65b48ab5")
iggy.to_dict()
Anirudra = Person("https://in.linkedin.com/in/anirudra-choudhury-109635b1")
Anirudra.to_dict()
51 changes: 51 additions & 0 deletions test/test_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""
Test Utils
"""
from typing import Dict, Any
from linkedin_scraper.utils import to_dict
from linkedin_scraper.objects import Contact, Institution
from dataclasses import dataclass
import unittest

@dataclass
class SampleClass:
_test_var: str
contact: Contact
institution: Institution
def to_dict(self) -> Dict[str, Any]:
return to_dict(self)

class TestUtils(unittest.TestCase):
"""
Test Utils
"""
def test_to_dict(self):
test_class = SampleClass(
_test_var = 'test var',
contact=Contact(
name='test_name'
),
institution=Institution(
institution_name= 'test_place'
)
)

test_class_dict = to_dict(test_class)
expected_output = {
'contact': {'name':'test_name',
'occupation': None,
'url': None},
'institution': {
'company_size': None,
'founded': None,
'headquarters': None,
'industry': None,
'institution_name': 'test_place',
'linkedin_url': None,
'type': None,
'website': None
}
}
self.assertEqual(test_class_dict, expected_output)
if __name__ == "__main__":
unittest.main()