aboutsummaryrefslogtreecommitdiff
path: root/doc/filters/confederationpaysanne.py
blob: 6db001e758cd47c2bb40f166f4e213287f597ec9 (plain)
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# vim: ft=python et softtabstop=4 cinoptions=4 shiftwidth=4 ts=4 ai
"""
USAGE
    confederationpaysanne.py [OPTION] URL

OPTIONS
    -t, --title=TEXT
        Updates feed title.
        Default is page title
    -d, --description=TEXT
        Updates feed description.
        Default is ""
    -v, --version
        Print version and exit.
    -h, --help
        Show this help and exit.

EXAMPLES
    confederationpaysanne.py -t "LeBonCoin.org Rhône-Alpes" -d "Test" \
"http://www.confederationpaysanne.fr/petites_annonces.php"
"""

from __future__ import print_function
from bs4 import BeautifulSoup
import PyRSS2Gen
import sys
import getopt
import logging
from dateutil.parser import parse
import datetime

__version__ = "0.2"

# Defaults
feed_title = None
feed_description = None
base_url = "http://confederationpaysanne.fr/"

# Logging
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
logging.disable(logging.INFO - 1)
logger = logging.getLogger('confederationpaysanne')

# Parse args
try:
    optlist, args = getopt.getopt(sys.argv[1:], 'u:t:d:hv',
                                  ['help', 'version', 'title=',
                                   'description='])
except getopt.GetoptError as msg:
    logger.error("%s\n\n%s", msg, __doc__)
    sys.exit(2)

for opt in optlist:
    if opt[0] in ('-t', '--title'):
        feed_title = opt[1]
    if opt[0] in ('-d', '--description'):
        feed_description = opt[1]
    elif opt[0] in ('-v', '--version'):
        print(__version__)
        sys.exit(0)
    elif opt[0] in ('-h', '--help'):
        print(__doc__)
        sys.exit(0)

html = sys.stdin.read()

# Find entries
soup = BeautifulSoup(html, "lxml")

# region = soup.find(class_="entete").attrs.get('title')
# page_title = soup.head.find("meta", {"name": "title"}).attrs.get("content")
page_title = soup.head.find("title").text.strip()

if not feed_title:
    feed_title = page_title

entries = []

if soup.body.find("div", {"id": "res-recherche"}):
    content = soup.body.find("div", {"id": "res-recherche"}).findAll("div", {"class": "d-texte" })
    for section in content:
        entry = {
            'title': "",
            'content': [],
            'link': "",
            'date': ""
        }
        nextNode = section

        ## date
        rawdate = nextNode.find("span", {"class": "f-date"}).text
        if rawdate:
            entry['date'] = rawdate

        ## title
        rawtitle = nextNode.find("h5")
        entry['title'] = " ".join(
            [line.strip() for line in rawtitle.text.strip().splitlines()]
        )

        ## content
        entry['content'] = nextNode.get_text().strip().splitlines()

        entries.append(entry)


# Build rss items based on entries
items = []

today = datetime.date.today()
one_day = datetime.timedelta(days=1)
yesterday = today - one_day

category = "annonce"

for entry in entries:
    # title = entry.find("div", {"class": "title"}).text.strip()
    title = entry["title"]
    link = entry["link"]
    content = "\n".join(entry["content"])
    # divs = entry.find("div", {"class": "date"}).find_all("div")
    # divdate = " ".join(map(lambda x: x.text, divs))

    # predate = re.sub("(?i)hier", yesterday.isoformat(), divdate)
    # predate = re.sub("(?i)aujourd'hui", today.isoformat(), predate)
    # # The following line appears to be incompatible with python2.X
    # # (ex: '28 août'):
    # #date = parse(predate, fuzzy=True, parserinfo=myparserinfo())
    date = parse(entry["date"], dayfirst=True, fuzzy=True)
    items.append(
        PyRSS2Gen.RSSItem(
            # title=title + " (" + placement + ") " + price,
            title=title,
            link=link,
            categories=[category],
            description=content,
            pubDate=date,
        )
    )

# Build rss feed
rss = PyRSS2Gen.RSS2(
    title=feed_title or soup.body.find(class_="sTitrePage").text or "",
    link=None,
    description=feed_description or "",
    # lastBuildDate = datetime.datetime.now(),
    items=items)

# Return rss feed
print(rss.to_xml(encoding='utf-8'))
# print(BeautifulSoup(rss.to_xml(), "lxml").prettify())