aboutsummaryrefslogtreecommitdiffstats
path: root/main.py
blob: 00ce6d1e4ce4ed5cc38d38914b79bbee0c2f1d87 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#!/usr/bin/env python3
# _*_ coding=utf-8 _*_

import argparse
import logging
from newspaper import Article, build
from bs4 import BeautifulSoup
from contextlib import closing
from requests import get
from requests.exceptions import RequestException
from re import findall


class Argparser(object):
    def __init__(self):
        parser = argparse.ArgumentParser()
        parser.add_argument(
            "--source",
            type=str, help="the url where the urls to be extracted reside")
        parser.add_argument("--bool", action="store_true",
                            help="bool", default=False)
        self.args = parser.parse_args()


# TODO-maybe actually really do some logging
def logError(err):
    print(err)


def isAGoodResponse(resp):
    content_type = resp.headers['Content-Type'].lower()
    return (resp.status_code == 200 and
            content_type is not None and content_type.find("html") > -1)


def simpleGet(url):
    try:
        with closing(get(url, stream=True)) as resp:
            if isAGoodResponse(resp):
                return resp.content
            else:
                return None
    except RequestException as e:
        logError("Error during requests to {0} : {1}".format(url, str(e)))
        return None


def getURLS(source):
    result = dict()
    raw_ml = simpleGet(source)
    ml = BeautifulSoup(raw_ml, "lxml")
    ml_str = repr(ml)
    tmp = open("/tmp/riecher", "w")
    tmp.write(ml_str)
    tmp.close()
    tmp = open("/tmp/riecher", "r")
    dump_list = []
    for line in tmp:
        dummy = findall(
            'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|'
            r'(?:%[0-9a-fA-F][0-9a-fA-F]))+', line)
        dump_list += dummy
    for elem in dump_list:
        result[elem] = elem
    tmp.close()
    return result


def main():
    argparser = Argparser()
    urls = getURLS(argparser.args.source)
    # import sys
    # print(urls)
    # sys.exit(0)
    for url in urls:
        parser = build(url)
        for article in parser.articles:
            a = Article(article.url)
            try:
                a.download()
                a.parse()
                print(a.text)
            except Exception as e:
                logging.exception(e)


if __name__ == "__main__":
    main()