import re

from bs4 import BeautifulSoup
from nltk.corpus import stopwords
import requests
from sqlalchemy.orm import sessionmaker


from models import create_db_tables, db_connect, WebsitesContent
from google import search

MAX_RESULTS_LIMIT = 50


def get_queries():
    """Returns a list of queries we want to index data.
    Note: for now it is a hardcoded list but it will be replaced with data fetched from Twitter.
    """
    return ['cars']


def index_query_data(query, db_session):
    """Fetch google pages for a query and index their content. """
    words = []
    for url in search(query, stop=MAX_RESULTS_LIMIT):
        try:
            words = extract_words_from_url(url)
            db_session.add(WebsitesContent(link=url, words=words))
            db_session.commit()
        except:
            print url

    return words


def extract_words_from_url(url):
    """Use BeautifulSoup to extract visible text from a web page. """
    def visible(element):
        """Method used to filter visible text elements. """
        if element.parent.name in ['style', 'script', '[document]', 'head', 'link']:
            return False
        elif re.match('<!--.*-->', element.encode('utf-8')):
            return False

        value = element.encode('utf-8')
        return not value.isspace()

    html = requests.get(url, verify=False).content
    soup = BeautifulSoup(html, 'html.parser')
    texts = soup.findAll(text=True)

    visible_texts = [text for text in texts if visible(text)]

    words = []
    stop_words = stopwords.words('english')
    for text in visible_texts:
        for word in re.findall(r"[\w']+", text):
            word = word.lower()
            if not word.isdigit() and word not in stop_words:
                words.append(word)


    return words


def main():
    """Based on a list of queries:
     - get the first 50 results from google
     - scrap their text
     - store text in the db
     - get demographics for page
     - store demographics
    """
    engine = db_connect()
    create_db_tables(engine)
    Session = sessionmaker(bind=engine)
    session = Session()

    quereies = get_queries()

    for query in quereies:
        index_query_data(query, session)

    session.close()


if __name__ == '__main__':
    main()

@@ -129,123 +129,848 @@
 er%0A%0A
-%0Afrom models import create_db_tables, db_connect, WebsitesContent%0Afrom google import search%0A%0AMAX_RESULTS_LIMIT = 50
+# scraping modules%0Aimport sys%0Asys.path.append(%22../demographic_scraper/%22)%0Asys.path.append(%22../%22)%0Afrom scrapy.crawler import CrawlerProcess%0Afrom scrapy.utils.log import configure_logging%0Afrom demographic_scraper.spiders.alexa_spider import AlexaSpider%0Afrom scrapy.utils.project import get_project_settings%0A%0Afrom models import create_db_tables, db_connect, WebsitesContent%0Afrom google import search%0A%0AMAX_RESULTS_LIMIT = 50%0A%0A%0Adef crawl_for_demographics(url):%0A    %22%22%22Fetch demographics from (currently just) Alexa.com%22%22%22%0A    configure_logging(%7B'LOG_FORMAT': '%25(levelname)s: %25(message)s'%7D)%0A    settings = get_project_settings()%0A    settings.set('ITEM_PIPELINES',%0A                 %7B'demographic_scraper.pipelines.WebsiteDemographicPipeline': 300%7D)%0A    process = CrawlerProcess(settings)%0A%0A    process.crawl(AlexaSpider, url=url)%0A    process.start()
 %0A%0A%0Ad

Add method to call Alexa spider