Skip to content

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

refactor: use blank line inbetween long simple blocks (same indent) and after branch (indent shrinks)

cthulhu-irl2c1982210831
diff --git a/autoscraper/auto_scraper.py b/autoscraper/auto_scraper.py
index f8b2f64..50cdd89 100644
--- a/autoscraper/auto_scraper.py
+++ b/autoscraper/auto_scraper.py
@@ -28,12 +28,15 @@ class AutoScraper(object):
def _get_soup(cls, url=None, html=None, request_args=None):
if html:
return BeautifulSoup(html, 'lxml')
+
request_args = request_args if request_args else {}
headers = dict(cls.request_headers)
if url:
headers['Host'] = urlparse(url).netloc
+
headers = request_args.get('headers', headers)
html = requests.get(url, headers=headers, **request_args).text
+
return BeautifulSoup(html, 'lxml')
@classmethod
@@ -43,8 +46,10 @@ class AutoScraper(object):
if attr not in {'class', 'style'}:
del attrs[attr]
continue
+
if attrs[attr] == []:
attrs[attr] = ''
+
return attrs
def _child_has_text(self, child, text):
@@ -68,6 +73,7 @@ class AutoScraper(object):
child.wanted_attr = key
child.is_full_url = True
return True
+
return False
def _get_children(self, soup, text):
@@ -75,6 +81,7 @@ class AutoScraper(object):
children = reversed(soup.findChildren())
children = list(
filter(lambda x: self._child_has_text(x, text), children))
+
return children
@classmethod
@@ -83,6 +90,7 @@ class AutoScraper(object):
for item in item_list:
if item not in unique_list:
unique_list.append(item)
+
return unique_list
def build(self, url=None, wanted_list=None, html=None, request_args=None):
@@ -113,6 +121,7 @@ class AutoScraper(object):
for w in wanted_list:
if w not in result:
return False
+
return True
@classmethod
@@ -130,28 +139,35 @@ class AutoScraper(object):
content.insert(
0, (grand_parent.name, cls._get_valid_attrs(grand_parent), i))
break
+
if grand_parent.name == 'html':
break
+
parent = grand_parent
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)
+
return stack
def _get_result_for_child(self, child, soup):
stack = self._build_stack(child)
result = self._get_result_with_stack(stack, soup)
+
return result, stack
def _fetch_result_from_child(self, child, wanted_attr, is_full_url):
if wanted_attr is None:
return child.getText().strip().rstrip()
+
if wanted_attr not in child.attrs:
return None
+
if is_full_url:
return urljoin(self.url, child.attrs[wanted_attr])
+
return child.attrs[wanted_attr]
def _get_result_with_stack(self, stack, soup):
@@ -160,6 +176,7 @@ class AutoScraper(object):
children = []
for parent in parents:
children += parent.findAll(item[0], item[1], recursive=False)
+
parents = children
wanted_attr = stack['wanted_attr']
@@ -167,6 +184,7 @@ class AutoScraper(object):
result = [self._fetch_result_from_child(
i, wanted_attr, is_full_url) for i in parents]
result = list(filter(lambda x: x, result))
+
return result
def _get_result_with_stack_index_based(self, stack, soup):
@@ -175,40 +193,50 @@ class AutoScraper(object):
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'])
+
return result
def get_result_similar(self, url=None, html=None, soup=None, request_args=None):
if url:
self.url = url
+
if not soup:
soup = self._get_soup(url=url, html=html,
request_args=request_args)
+
result = []
for stack in self.stack_list:
result += self._get_result_with_stack(stack, soup)
+
return self.unique(result)
def get_result_exact(self, url=None, html=None, soup=None, request_args=None):
if url:
self.url = url
+
if not soup:
soup = self._get_soup(url=url, html=html,
request_args=request_args)
+
result = []
for stack in self.stack_list:
try:
result.append(
self._get_result_with_stack_index_based(stack, soup))
+
except IndexError:
continue
+
return self.unique(result)
def get_result(self, url=None, html=None, request_args=None):
soup = self._get_soup(url=url, html=html, request_args=request_args)
similar = self.get_result_similar(soup=soup)
exact = self.get_result_exact(soup=soup)
+
return similar, exact
def generate_python_code(self):
@@ -217,5 +245,7 @@ class AutoScraper(object):
file_path = os.path.join(os.path.dirname(__file__), "code_template.py")
with open(file_path, 'r') as f:
code = f.read()
+
code = code.replace('"{STACK_LIST}"', str(self.stack_list))
+
return code
diff --git a/autoscraper/code_template.py b/autoscraper/code_template.py
index 709d061..7bcda11 100644
--- a/autoscraper/code_template.py
+++ b/autoscraper/code_template.py
@@ -18,12 +18,15 @@ class GeneratedAutoScraper(object):
def _get_soup(url=None, html=None, request_args=None):
if html:
return BeautifulSoup(html, 'lxml')
+
request_args = request_args if request_args else {}
headers = dict(cls.request_headers)
if url:
headers['Host'] = urlparse(url).netloc
+
headers = request_args.get('headers', headers)
html = requests.get(url, headers=headers, **request_args).text
+
return BeautifulSoup(html, 'lxml')
@classmethod
@@ -32,15 +35,19 @@ class GeneratedAutoScraper(object):
for item in item_list:
if item not in unique_list:
unique_list.append(item)
+
return unique_list
def _fetch_result_from_child(self, child, wanted_attr, is_full_url):
if wanted_attr is None:
return child.getText().strip().rstrip()
+
if wanted_attr not in child.attrs:
return None
+
if is_full_url:
return urljoin(self.url, child.attrs[wanted_attr])
+
return child.attrs[wanted_attr]
def _get_result_with_stack(self, stack, soup):
@@ -49,12 +56,14 @@ class GeneratedAutoScraper(object):
children = []
for parent in parents:
children += parent.findAll(item[0], item[1], recursive=False)
+
parents = children
wanted_attr = stack['wanted_attr']
is_full_url = stack['is_full_url']
result = [self._fetch_result_from_child(i, wanted_attr, is_full_url) for i in parents]
result = list(filter(lambda x: x, result))
+
return result
def _get_result_with_stack_index_based(self, stack, soup):
@@ -62,34 +71,43 @@ class GeneratedAutoScraper(object):
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'])
return result
def get_result_similar(self, url=None, html=None, soup=None, request_args=None):
if url:
self.url = url
+
if not soup:
soup = self._get_soup(url=url, html=html, request_args=request_args)
+
result = []
for stack in self.stack_list:
result += self._get_result_with_stack(stack, soup)
+
return self.unique(result)
def get_result_exact(self, url=None, html=None, soup=None, request_args=None):
if url:
self.url = url
+
if not soup:
soup = self._get_soup(url=url, html=html, request_args=request_args)
+
result = []
for stack in self.stack_list:
try:
result.append(self._get_result_with_stack_index_based(stack, soup))
+
except IndexError:
continue
+
return self.unique(result)
def get_result(self, url=None, html=None, request_args=None):
soup = self._get_soup(url=url, html=html, request_args=request_args)
similar = self.get_result_similar(soup=soup)
exact = self.get_result_exact(soup=soup)
+
return similar, exact