Skip to content

A Smart, Automatic, Fast and Lightweight Web Scraper for Python

add ability to remove unwanted scraping rules

alireza28cf3f6d2399
diff --git a/autoscraper/auto_scraper.py b/autoscraper/auto_scraper.py
index 9401f0e..f63f14c 100644
--- a/autoscraper/auto_scraper.py
+++ b/autoscraper/auto_scraper.py
@@ -1,10 +1,11 @@
import json
+from collections import defaultdict
from urllib.parse import urljoin, urlparse
import requests
from bs4 import BeautifulSoup
-from autoscraper.utils import unique
+from autoscraper.utils import unique, get_random_str
class AutoScraper(object):
@@ -18,12 +19,21 @@ class AutoScraper(object):
self.url = url
def save(self, file_path):
+ data = dict(url=self.url, stack_list=self.stack_list)
with open(file_path, 'w') as f:
- json.dump(self.stack_list, f)
+ json.dump(data, f)
def load(self, file_path):
with open(file_path, 'r') as f:
- self.stack_list = json.load(f)
+ data = json.load(f)
+
+ # for backward compatibility
+ if isinstance(data, list):
+ self.stack_list = data
+ return
+
+ self.stack_list = data['stack_list']
+ self.url = data['url']
@classmethod
def _get_soup(cls, url=None, html=None, request_args=None):
@@ -110,7 +120,7 @@ class AutoScraper(object):
if not grand_parent:
break
- for i, c in enumerate(grand_parent.findAll(parent.name, recursive=False)):
+ for i, c in enumerate(grand_parent.findAll(parent.name, cls._get_valid_attrs(parent), recursive=False)):
if c == parent:
content.insert(
0, (grand_parent.name, cls._get_valid_attrs(grand_parent), i))
@@ -124,6 +134,7 @@ class AutoScraper(object):
wanted_attr = getattr(child, 'wanted_attr', None)
is_full_url = getattr(child, 'is_full_url', False)
stack = dict(content=content, wanted_attr=wanted_attr, is_full_url=is_full_url)
+ stack['stack_id'] = 'rule_' + get_random_str(4)
return stack
def _get_result_for_child(self, child, soup):
@@ -162,39 +173,45 @@ class AutoScraper(object):
p = soup.findChildren(recursive=False)[0]
stack_content = stack['content']
for index, item in enumerate(stack_content[:-1]):
- p = p.findAll(stack_content[index + 1][0], recursive=False)[item[2]]
-
- result = self._fetch_result_from_child(p, stack['wanted_attr'], stack['is_full_url'])
+ content = stack_content[index + 1]
+ p = p.findAll(content[0], content[1], recursive=False)
+ if not p:
+ return []
+ idx = min(len(p) - 1, item[2])
+ p = p[idx]
+
+ result = [self._fetch_result_from_child(p, stack['wanted_attr'], stack['is_full_url'])]
+ result = list(filter(lambda x: x, result))
return result
- def get_result_similar(self, url=None, html=None, soup=None, request_args=None):
+ def _get_result_by_func(self, func, url, html, soup, request_args, grouped):
if url:
self.url = url
if not soup:
soup = self._get_soup(url=url, html=html, request_args=request_args)
- result = []
+ result_list = []
+ grouped_result = defaultdict(list)
for stack in self.stack_list:
- result += self._get_result_with_stack(stack, soup)
- return unique(result)
+ result = func(stack, soup)
- def get_result_exact(self, url=None, html=None, soup=None, request_args=None):
- if url:
- self.url = url
+ if not grouped:
+ result_list += result
+ continue
- if not soup:
- soup = self._get_soup(url=url, html=html, request_args=request_args)
+ stack_id = stack['stack_id']
+ grouped_result[stack_id] += result
- result = []
- for stack in self.stack_list:
- try:
- result.append(self._get_result_with_stack_index_based(stack, soup))
+ return dict(grouped_result) if grouped else unique(result_list)
- except IndexError:
- continue
+ def get_result_similar(self, url=None, html=None, soup=None, request_args=None, grouped=False):
+ func = self._get_result_with_stack
+ return self._get_result_by_func(func, url, html, soup, request_args, grouped)
- return unique(result)
+ def get_result_exact(self, url=None, html=None, soup=None, request_args=None, grouped=False):
+ func = self._get_result_with_stack_index_based
+ return self._get_result_by_func(func, url, html, soup, request_args, grouped)
def get_result(self, url=None, html=None, request_args=None):
soup = self._get_soup(url=url, html=html, request_args=request_args)
@@ -202,6 +219,12 @@ class AutoScraper(object):
exact = self.get_result_exact(soup=soup)
return similar, exact
+ def remove_rules(self, rules):
+ self.stack_list = list(filter(lambda x: x['stack_id'] not in rules, self.stack_list))
+
+ def keep_rules(self, rules):
+ self.stack_list = list(filter(lambda x: x['stack_id'] in rules, self.stack_list))
+
def generate_python_code(self):
# deprecated
print('This function is deprecated. Please use save() and load() instead.')
diff --git a/autoscraper/utils.py b/autoscraper/utils.py
index ee44a18..141ced8 100644
--- a/autoscraper/utils.py
+++ b/autoscraper/utils.py
@@ -1,6 +1,14 @@
+import random
+import string
+
+
def unique(item_list):
unique_list = []
for item in item_list:
if item not in unique_list:
unique_list.append(item)
return unique_list
+
+def get_random_str(n):
+ chars = string.ascii_lowercase + string.digits
+ return ''.join(random.choice(chars) for i in range(n))