aboutsummaryrefslogtreecommitdiff
path: root/doc/filters/leboncoin.py
blob: d2d3d1a2f00cbca089b015768f13d1f3c73cebaa (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
155
156
157
158
159
160
161
162
163
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# vim: ft=python et softtabstop=4 cinoptions=4 shiftwidth=4 ts=4 ai
"""
USAGE
    curl URL | leboncoin.py [OPTION]

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.
"""

from __future__ import print_function, unicode_literals
from bs4 import BeautifulSoup
import PyRSS2Gen
import sys
import getopt
import logging
import re
from dateutil.parser import parserinfo, parse
import datetime

__version__ = "0.2"

# Defaults
feed_title = None
feed_description = None
months = [
    ('Janvier', 'Jan', 'Janv'),
    ('Février', 'Fév', 'Fev',),
    ('Mars', 'Mar',),
    ('Avril', 'Avr',),
    ('Mai',),
    ('Juin', ),
    ('Juillet', 'Juil'),
    ('Août', 'Aout'),
    ('Septembre', 'Sept', ),
    ('Octobre', 'Oct'),
    ('Novembre', 'Nov'),
    ('Décembre', 'Déc', 'Dec')
]

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

# 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().decode('iso-8859-1')

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

# region = soup.find(class_="entete").attrs.get('title')
page_title = soup.head.find("title")
if not page_title:
    logger.error("Can't find page_title")
page_title = page_title.contents[0].strip()

if not feed_title:
    feed_title = "LeBonCoin.fr - " + page_title

entries = soup.body.find_all(itemtype="http://schema.org/Offer")

# Build rss items based on entries
items = []

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


class MyParserInfo(parserinfo):
    MONTHS = [parserinfo.MONTHS[x] + months[x] for x in range(12)]

for entry in entries:
    # title = entry.find("div", {"class": "title"}).text.strip()
    title = entry.a.attrs.get("title")
    if not title:
        logger.error("Can't find title for entry.")
    link = entry.a.attrs.get("href")
    if not link:
        logger.error("Can't find link for entry %s.", title)
    if entry.img:
        photo_title = entry.img.attrs.get("alt")
        photo_link = entry.img.attrs.get("src")
    category = re.sub(
        r"\s+",
        " ",
        entry.find(itemprop="category").text.strip()
    )
    rawprice = entry.find(itemprop="price")
    if rawprice:
        price = rawprice.text.strip()
    else:
        price = ""
    place = re.sub(
        r"\s+",
        " ",
        entry.find(itemprop="availableAtOrFrom").text.strip()
    )
    if not place:
        logger.error("Can't find place for entry %s", title)
    divdate = entry.find(itemprop="availabilityStarts").text.strip()

    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())
    items.append(
        PyRSS2Gen.RSSItem(
            title=title + " (" + place + ") " + price,
            link=link,
            categories=[category],
            description=title + " (" + place + ") " + price +
            "; publication: " + divdate,
            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())
# souprss = BeautifulSoup(rss.to_xml())