-
Notifications
You must be signed in to change notification settings - Fork 5
/
parser.py
executable file
·203 lines (191 loc) · 8.01 KB
/
parser.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
200
201
202
203
#!/usr/bin/env python3
"""Parsing members data from current URL on FetLife website.
Was written many years ago so don't be harsh on it.
Been constantly updated while people still use it."""
import os
import csv
import sys
import logging
from time import sleep
from selenium import webdriver
from lxml import html
logging.basicConfig(format='%(asctime)s | %(levelname)s: %(message)s',
level=logging.INFO)
options = webdriver.ChromeOptions()
options.add_argument("headless")
URL = 'https://fetlife.com'
# Configs
USERNAME = ''
PASSWORD = ''
SEX = 'F'
def login_procedure():
"""Get a new driver instance or simply log in."""
logging.info('Parser initialization...OK')
# Expects chromedriver.exe file in the script directory
# Check: https://chromedriver.chromium.org/downloads
# Should match the local Chrome version
driver = webdriver.Chrome('chromedriver.exe', options=options)
driver.get('https://fetlife.com/users/sign_in')
username = driver.find_element_by_id("user_login")
username.send_keys(USERNAME)
sleep(1)
password = driver.find_element_by_id("user_password")
password.send_keys(PASSWORD)
sleep(1)
logging.info('Login procedure started...')
driver.find_element_by_xpath('//button').click()
sleep(5)
return driver
def write_data(url, drivery):
"""Write user info into CSV file."""
data = {}
drivery.get(url)
sleep(3)
tree = html.fromstring(drivery.page_source.encode())
data['Link to profile'] = url
try:
data['Name'] = tree.xpath("string(//img[contains(@class, 'db ipp w-100')]/@alt)")
except Exception as error:
logging.warning(error)
data['Name'] = 'N/A'
try:
data['Age'] = tree.xpath("string(//*[contains(@class, 'dib us-none')])").split(' ')[0][0:2]
except Exception as error:
logging.warning(error)
data['Age'] = 'N/A'
try:
data['Role'] = tree.xpath("string(//*[contains(@class, 'dib us-none')])").split(' ')[1]
except Exception as error:
logging.warning(error)
data['Role'] = 'N/A'
try:
data['Location'] = ', '.join([i for i in tree.xpath("//*[contains(@class, 'mt0-s mt3 tl')]//p//text()")])
except Exception as error:
logging.warning(error)
data['Location'] = 'N/A'
try:
d_s_first = [i.strip() for i in tree.xpath(
"//*[text()='D/s Relationships']/following-sibling::div//div/text()")]
d_s_last = [i.strip() for i in tree.xpath(
"//*[text()='D/s Relationships']/following-sibling::div//span//text()")]
if d_s_last:
data['D/s Relationship Status'] = '; '.join(list(map(': '.join, list(zip(d_s_first, d_s_last)))))
else:
data['D/s Relationship Status'] = '; '.join(d_s_first)
except Exception as error:
logging.warning(error)
data['D/s Relationship Status'] = 'N/A'
try:
d_s_first = [i.strip() for i in tree.xpath("//*[text()='Relationships']/following-sibling::div//div/text()")]
d_s_last = [i.strip() for i in tree.xpath(
"//*[text()='Relationships']/following-sibling::div//span//text()")]
if d_s_last:
data['Relationship Status'] = '; '.join(list(map(': '.join, list(zip(d_s_first, d_s_last)))))
else:
data['Relationship Status'] = '; '.join(d_s_first)
except Exception as error:
logging.warning(error)
data['Relationship Status'] = 'N/A'
try:
data['Orientation'] = '; '.join([i.xpath("string(.)")
for i in
tree.xpath("//*[text()='Orientation']//following-sibling::div")])
except Exception as error:
logging.warning(error)
data['Orientation'] = 'N/A'
try:
data['Active'] = '; '.join([i.xpath("string(.)")
for i in
tree.xpath("//*[text()='Active']//following-sibling::div")])
except Exception as error:
logging.warning(error)
data['Active'] = 'N/A'
try:
data['Is Looking For'] = '; '.join([i.xpath("string(.)")
for i in
tree.xpath("//*[text()='Looking for']/following-sibling::div//div")])
except Exception as error:
logging.warning(error)
data['Is Looking For'] = 'N/A'
try:
data['Groups member of'] = '; '.join([i.xpath("./text()")[0].strip() for i in
tree.xpath("//ul[contains(@class, 'list bb b-gray-800')]//li/a")])
except Exception as error:
logging.warning(error)
data['Groups member of'] = 'N/A'
try:
data['About me'] = tree.xpath("string(//h2[text()='About ']/following-sibling::div)")
except Exception as error:
logging.warning(error)
data['About me'] = 'N/A'
try:
data['Fetishes'] = tree.xpath("string(//h2[text()='Fetishes ']/following-sibling::div)")
except Exception as error:
logging.warning(error)
data['Fetishes'] = 'N/A'
return data
def start_session(link, driver, first_time=False):
"""Looped main script function."""
if not link.endswith('members') and not link.endswith('kinksters'):
link = link.rstrip('/') + '/members'
if first_time:
driver = login_procedure()
f_name = '{}.csv'.format('-'.join(link.split('/')[3:]))
names = []
with open(f_name,
'w', newline='', encoding='utf-8') as csvfile:
fieldnames = ['Name', 'Link to profile', 'Age', 'Role', 'Location',
'D/s Relationship Status', 'Relationship Status',
'Orientation', 'Active', 'Is Looking For',
'Groups member of', 'About me', 'Fetishes']
writer = csv.DictWriter(csvfile,
fieldnames=fieldnames)
writer.writeheader()
logging.info('Parsing started...')
n = 1
while True:
if n % 100 == 0:
logging.info("Reached another hundred")
driver.close()
driver.quit()
driver = login_procedure()
logging.info('Parser initialization...OK')
logging.info(f'Parsing page {n}')
driver.get(link +
'?page={}'.format(n))
users = html.fromstring(driver.page_source).xpath(
"//div[@class='nl1 nr1 flex flex-wrap']//div[@class='w-50-ns w-100 ph1']")
if not users:
logging.warning(f"Group's final page reached")
break
else:
n += 1
for i in users:
name = i.xpath("string(.//a[@class='link f5 font-bold secondary mr1'])")
if name in names:
logging.info('{} is already enlisted!'.format(name))
continue
sex = i.xpath("string(.//span[@class='f6 font-bold gray-300'])")
iff = sex.strip().split('\n')[0].split(' ')[0]
if len(iff) == 3 and iff.endswith(SEX):
logging.info('Found {}'.format(name))
logging.info(URL + i.xpath("string(.//a[@class='link f5 font-bold secondary mr1']/@href)"))
sleep(1)
writer.writerow(write_data(URL +
i.xpath("string(.//a[@class='link f5 font-bold secondary mr1']/@href)"),
driver
))
if __name__ == '__main__':
first_time = True
while True:
try:
start_session(input('Paste URL and press "Enter":\n'), driver, first_time)
first_time = False
except Exception as e:
exc_type, exc_obj, exc_tb = sys.exc_info()
logging.critical('{} on line {}'.format(
e, str(exc_tb.tb_lineno)))
input('Press any key to exit...')
driver.close()
driver.quit()
exit(1)