-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathsync_producthunt.py
199 lines (163 loc) · 5.72 KB
/
sync_producthunt.py
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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
"""
同步product hunt到notion
"""
import logging
import time
import requests
from pyquery import PyQuery as pq
from notion_client import Client
from config import CONFIG
from api.notion import BlockHelper
class ProductItem:
"""product item"""
def __init__(
self,
name: str,
desc: str,
topics: list[str],
comments: int,
votes: int,
url: str = "",
cover: str = "",
) -> None:
self.name = name
self.desc = desc
self.topics = topics
self.comments = comments
self.votes = votes
self.cover = cover
self.url = f"https://www.producthunt.com{url}"
# def fullfill_repo_info(self, git_token):
# pass
def __repr__(self) -> str:
return f"""<ProductItem name={self.name} desc={self.desc} topics={self.topics} \
comments={self.comments} votes={self.votes} url={self.url} cover={self.cover}>"""
def query_page(client: Client, database_id: str, name: str) -> bool:
"""check page exist or not"""
time.sleep(0.3)
response = client.databases.query(
database_id=database_id,
filter={"property": "Name", "rich_text": {"equals": name}},
)
if len(response["results"]):
return True
return False
def _append_page(client: Client, database_id: str, prod: ProductItem) -> None | str:
"""插入page"""
parent = {"database_id": database_id, "type": "database_id"}
properties = {
"Name": BlockHelper.title(prod.name),
"Description": BlockHelper.rich_text(prod.desc),
"Topics": BlockHelper.multi_select(prod.topics),
"Comments": BlockHelper.number(prod.comments),
"Votes": BlockHelper.number(prod.votes),
"URL": BlockHelper.url(prod.url),
"Cover": BlockHelper.files("Cover", prod.cover),
}
response = client.pages.create(
parent=parent, icon=BlockHelper.icon(prod.cover), properties=properties
)
return response["id"]
def _scrape() -> list[ProductItem]:
headers = {
# pylint: disable=line-too-long
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0",
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip,deflate,sdch",
"Accept-Language": "zh-CN,zh;q=0.8",
}
result = []
url = "https://www.producthunt.com/all"
req = requests.get(url, headers=headers, timeout=60)
if req.status_code != 200:
logging.error("access product hunt error. %d", req.status_code)
return
content = pq(req.content)
items = content("main div.flex-col div.flex-col div[class^='styles_item']")
if items.length == 0:
items = content("main div.flex-col div.flex-col section")
for item in items:
logging.debug("parse product: %s", item)
i = pq(item)
url = i('a[href^="/posts/"]').eq(0).attr("href")
mid = i("div.flex-col a")
name = mid.eq(0).text()
description = mid.eq(1).text()
# name = i("div.flex-col a strong").text()
# description = i("div.flex-col a").text()
comments = i("div.flex-col div.flex-row div").eq(0).text()
if not comments:
comments = i("button div.flex-col").eq(0).text()
votes = i('button[data-test="vote-button"]').text()
cover = i('a[href^="/posts/"] img').eq(0).attr("src")
if not cover:
cover = i('a[href^="/posts/"] video').eq(0).attr("poster")
_topics = i('div.flex-col div.flex-row a[href^="/topics/"]')
topics = []
for topic in _topics:
topic = pq(topic).text()
topics.append(topic)
if name == "" or description == "" or len(topics) == 0:
logging.error(
"parse name or description error: %s-%s-%d",
name,
description,
len(topics),
)
continue
if not votes.isnumeric() or not comments.isnumeric():
logging.error(
"parse votes or comments error: %s-%s-%s", name, votes, comments
)
continue
try:
votes = int(votes)
comments = int(comments)
except ValueError:
logging.error("parse votes or comments error")
continue
result.append(
ProductItem(
name, description, topics, votes, comments, url=url, cover=cover
)
)
return result
def _filter_product(prod: ProductItem) -> bool:
filters = {
"MinVotes": "votes",
"MinComments": "comments",
}
for k, v in filters.items():
thresh_hold = CONFIG.getint("producthunt.filter", k)
current = getattr(prod, v, 0)
if thresh_hold > 0 and current < thresh_hold:
return True
return False
# pylint: disable=line-too-long
def _sync(
client: Client,
database_id: str,
products: list[ProductItem],
) -> None:
for prod in products:
if _filter_product(prod):
logging.info("filter product: %s", prod.name)
continue
time.sleep(0.3) # avoid rate limit for notion API
if query_page(client, database_id, prod.name):
continue
# insert to db
logging.info(prod)
_id = _append_page(client, database_id, prod)
print(_id)
def sync_producthunt(notion_token, database_id):
"""sync product hunt to notion"""
client = Client(auth=notion_token, log_level=logging.ERROR)
products = _scrape()
if not products:
logging.error(
"ph scape error",
)
return
logging.info("ph scape total num [%s]", len(products))
_sync(client, database_id, products)