fb_helper

 1#!/usr/local/bin/python3
 2import time
 3import re
 4
 5def _login(browser, email, password):
 6    """
 7    Login to facebook
 8    Inputs are email and password
 9    """
10    browser.get("http://facebook.com")
11    browser.find_element("name", "email").send_keys(email)
12    browser.find_element("name", "pass").send_keys(password)
13    browser.find_element("name", 'login').click()
14    print("Logged in")
15    time.sleep(5)
16
17
18def _get_comment_amount(browser):
19    """
20    Find the amount of comments on a post
21    Parse the text to get the number of comments
22    """
23    temp = browser.find_elements("xpath", "//span[contains(text(), 'of')]")
24    for item in temp:
25        """
26        check if item matches the regex pattern 100 of 499
27        """
28        if re.match(r'\d+\sof\s\d+', item.text):
29            num = item.text
30            print("Getting Comments " + num)
31            break
32
33    # try catch block
34    try:
35        num_list = num.split(' ')
36        num1 = int(num_list[0])
37        num2 = int(num_list[2])
38    except:
39        num1 = 0
40        num2 = 0
41    return num1, num2
42
43
44def _get_more_comments(browser):
45    """
46    Click the 'View more comments' button
47    """
48    browser.find_element(
49        "xpath", "//span[contains(text(), 'View more comments')]").click()
50    time.sleep(5)
51
52
53def _get_comments(browser):
54    """
55    Get all comments from a post
56    Loop until all comments are loaded
57    """
58    while True:
59        num1, num2 = _get_comment_amount(browser)
60        if num1 + 50 > num2:
61            break
62        else:
63            _get_more_comments(browser)
64
65if __name__ == '__main__':
66    print("This module cannot be run directly. Please run main.py instead.")