示例#1
0
def test_short_drug_name():
    """
    Tests that the get_url function does not search for drug names shorter than 4 characters
    """
    scraper = DrugsScraper()
    url = scraper.get_url('ACE')
    assert not url
示例#2
0
def test_scrape_no_reviews():
    """
    Tests that scrape function works for page with no reviews
    """
    scraper = DrugsScraper()
    scraper.scrape('https://www.drugs.com/comments/xylitol/')
    assert len(scraper.reviews) == 0
示例#3
0
def test_get_url_real_drug_name():
    """
    Tests that the get_url function returns the correct url for a standard drug name ('actos')
    """
    scraper = DrugsScraper()
    url = scraper.get_url('actos')
    assert url == 'https://www.drugs.com/comments/pioglitazone/actos.html'
示例#4
0
def test_name_with_numbers():
    """
    Tests get_url function on drug name with numbers
    """
    scraper = DrugsScraper()
    url = scraper.get_url('B3-500-Gr')
    assert url == 'https://www.drugs.com/comments/niacin/b3-500-gr.html'
示例#5
0
def test_drug_name_with_space():
    """
    Tests that the get_url function returns the correct url for a drug name with a space in it
    """
    scraper = DrugsScraper()
    url = scraper.get_url('Advair Diskus')
    assert url == 'https://www.drugs.com/comments/fluticasone-salmeterol/advair-diskus.html'
示例#6
0
def test_url_fake_drug_name():
    """
    Tests that the get_url function returns 'None' for a drug name that does not have a review page
    """
    scraper = DrugsScraper()
    url = scraper.get_url('garbage')
    assert not url
示例#7
0
def test_scrape_invalid_url_no_title():
    """
    Tests that when the scrape function is called on a url that
    lacks a title (invalid url), it raises an AttributeError and returns 0
    """
    scraper = DrugsScraper()
    returned = scraper.scrape('https://www.webmd.com/drugs/drugreview-bhilknhj')
    assert returned == 0
示例#8
0
def test_scrape_page_incorrect_website():
    """
    Tests that the scrape_page function raises an assertion error
    when a url is entered with an incorrect domain name (not 'https://drugs.com...')
    """
    scraper = DrugsScraper()
    with pytest.raises(AssertionError):
        scraper.scrape_page('https://www.webmd.com/drugs/drugreview-64439-abilify.aspx?drugid=64439&drugname=abilify')
示例#9
0
def test_scrape_page_no_reviews():
    """
    Tests that the scrape page function returns 0 when
    no reviews are found on the page
    """
    scraper = DrugsScraper()
    returned = scraper.scrape_page('https://www.drugs.com/comments/xylitol/')
    assert returned == 0
示例#10
0
def test_scrape_wrong_title_url():
    """
    Tests that when the scrape function is called with an invalid url
    that does have a title but the title is wrong (doesn't have the phrase 'User Reviews for')
    that an AssertionError is raised and the function returns 0
    """
    scraper = DrugsScraper()
    returned = scraper.scrape('https://www.drugs.com/comments/fghjkjhgdfgh/')
    assert returned == 0
示例#11
0
def test_scrape_with_parameters():
    """
    Tests that, when calling scrape function with a scraper with non-default parameters
    the correct types of data are stored in the 'reviews' attribute
    """
    scraper = DrugsScraper(collect_urls=True, collect_user_ids=True)
    scraper.scrape('https://www.drugs.com/comments/acetaminophen/')
    data_collected = list(scraper.reviews[0].keys())
    assert len(data_collected) == 6
    assert 'user id' in data_collected
    assert 'url' in data_collected
示例#12
0
def test_scrape_page_with_parameters():
    """
    Tests to make sure that calling the scrape_page function
    on a scraper object with non-default parameters (collect_url
    and collect_user_id true) collects the correct types of
    data ('comment', 'rating', 'date', 'drug', 'url', and 'user id')
    """
    scraper = DrugsScraper(collect_user_ids=True, collect_urls=True)
    scraper.scrape_page('https://www.drugs.com/comments/acetaminophen/?page=2')
    data_collected = list(scraper.reviews[0].keys())
    assert len(data_collected) == 6
    assert 'user id' in data_collected
    assert 'url' in data_collected
示例#13
0
def test_scrape_correct_review_data():
    """
    Tests to make sure that when the scrape function is called,
    that the last review in the scraped reviews list as the correct data
    (this data is the data from the oldest review for this drug)
    """
    scraper = DrugsScraper(collect_user_ids=True)
    scraper.scrape('https://www.drugs.com/comments/acetaminophen/')
    assert scraper.reviews[-1]['comment'][:11] == 'I only have'
    assert scraper.reviews[-1]['comment'][-10:] == ' in check.'
    assert scraper.reviews[-1]['rating'] == 10.0
    assert scraper.reviews[-1]['drug'] == 'Acetaminophen'
    assert scraper.reviews[-1]['date'] == 'March 4, 2008'
    assert scraper.reviews[-1]['user id'] == 'Anonymous'
示例#14
0
    def collect(self, url, testing=False):
        """Scrapes drug reviews and saves them as dictionary property

        Args:
            url: WebMD URL where all the reviews are
        """
        if self.meta['locked']:
            print('Dataset locked. Please load a different dataset.')
            return

        self.meta['startTimestamp'] = time()
        self.meta['drugs'] = [self.drug_name]

        scraper = None
        if self.scraper == 'WebMD':
            scraper = WebMDScraper()
        elif self.scraper == 'EverydayHealth':
            scraper = EverydayHealthScraper()
        elif self.scraper == 'Drugs':
            scraper = DrugsScraper()
        elif self.scraper == 'DrugRatingz':
            scraper = DrugRatingzScraper()

        if testing:
            scraper = WebMDScraper(False, 1)

        self.reviews = scraper.scrape(url)
        self.meta['endTimestamp'] = time()
示例#15
0
def test_scrape_page_default_parameters():
    """
    Tests to make sure that calling the scrape_page function
    on a scraper object with default parameters collects the
    correct types of data ('comment', 'rating', 'date', and 'drug')
    and that the correct number of reviews (25) were collected
    """
    scraper = DrugsScraper()
    scraper.scrape_page('https://www.drugs.com/comments/acetaminophen/?page=2')
    data_collected = list(scraper.reviews[0].keys())
    assert len(data_collected) == 4
    assert 'comment' in data_collected
    assert 'rating' in data_collected
    assert 'date' in data_collected
    assert 'drug' in data_collected
    assert len(scraper.reviews) == 25
示例#16
0
def test_scrape_default_parameter():
    """
    Tests that, when calling scrape function with a scraper with default parameters
    the correct types of data are stored in the 'reviews' attribute
    and that the correct number of reviews are collected (more
    than 25, this proves that it's scraping multiple pages)
    """
    scraper = DrugsScraper()
    scraper.scrape('https://www.drugs.com/comments/acetaminophen/')
    assert len(scraper.reviews) > 25
    data_collected = list(scraper.reviews[0].keys())
    assert len(data_collected) == 4
    assert 'comment' in data_collected
    assert 'rating' in data_collected
    assert 'date' in data_collected
    assert 'drug' in data_collected
示例#17
0
def test_default_initialization():
    """
    Test that when a new scraper object is initialized, the correct
    attributes are set (empty list[dict] 'reviews') and that collect_urls
    and collect_user_ids attributes (Booleans) are false by default
    """
    scraper = DrugsScraper()
    assert len(scraper.reviews) == 0
    assert not scraper.collect_urls
    assert not scraper.collect_user_ids
示例#18
0
def test_initialization_parameters():
    """
    Test that when a new scraper object is initialized with non-default arguments
    the correct attributes are set (empty list[dict] 'reviews') and that collect_urls
    and collect_user_ids attributes (Booleans) are set true
    """
    scraper = DrugsScraper(collect_urls=True, collect_user_ids=True)
    assert len(scraper.reviews) == 0
    assert scraper.collect_urls
    assert scraper.collect_user_ids
示例#19
0
def test_scrape_empty_reviews():
    """
    Tests to make sure that if the scrape function is called on a scraper
    that already has collected data in 'reviews', that those reviews are discarded
    """
    scraper = DrugsScraper()
    scraper.scrape('https://www.drugs.com/comments/acetaminophen/')
    num_reviews = len(scraper.reviews)
    scraper.scrape('https://www.drugs.com/comments/acetaminophen/')
    assert num_reviews == len(scraper.reviews)
示例#20
0
    def collect_drug_names(self, file_path, output_path):
        """Given list of drug names, collect urls for those review page on
            the scraper's website

        Args:
            file_path: input csv with list of drug names
            output_path: output csv with urls
        """
        if self.scraper == 'WebMD':
            scraper = WebMDScraper()
            scraper.get_drug_urls(file_path, output_path)
        elif self.scraper == 'EverydayHealth':
            scraper = EverydayHealthScraper()
            scraper.get_drug_urls(file_path, output_path)
        elif self.scraper == 'Drugs':
            scraper = DrugsScraper()
            scraper.get_drug_urls(file_path, output_path)
        elif self.scraper == 'DrugRatingz':
            scraper = DrugRatingzScraper()
            scraper.get_drug_urls(file_path, output_path)
示例#21
0
def test_get_drug_urls_drugs():
    scraper = DrugsScraper()
    scraper.get_drug_urls('test-drug-names.csv', 'urls.csv')
    assert os.path.exists('urls.csv')
    os.remove('urls.csv')
示例#22
0
def test_drugs_scrape():
    """Test drugs.com scrape"""
    input_url = 'https://www.drugs.com/comments/dabigatran/'
    drugs_scraper = DrugsScraper()
    review_list = drugs_scraper.scrape(input_url)
    assert len(review_list) > 5
示例#23
0
    def collect_urls(self, file_path, start=0):
        """Scrape all reviews for all drugs urls in file

        Args:
            start: index to start at if continuing from previous run
        """
        if self.meta['locked']:
            print('Dataset locked. Please load a different dataset.')
            return

        scraper = None
        if self.scraper == 'WebMD':
            scraper = WebMDScraper()
        elif self.scraper == 'EverydayHealth':
            scraper = EverydayHealthScraper()
        elif self.scraper == 'Drugs':
            scraper = DrugsScraper()
        elif self.scraper == 'DrugRatingz':
            scraper = DrugRatingzScraper()

        urls = []

        with open(file_path) as csv_file:
            reader = csv.DictReader(csv_file)
            for row in reader:
                if row['URL'] != 'Not found':
                    urls.append({'name': row['Drug'], 'url': row['URL']})
        print('Found {} urls.'.format(len(urls)))

        if os.path.isfile(self.drug_name.lower() + '-dataset.pickle'):
            self.load()
        else:
            print('Saving meta...')
            drug_names = [x['name'] for x in urls]
            self.meta['drugs'] = drug_names
            self.meta['startTimestamp'] = time()
            self.save()

        # Loop through urls starting at start index
        for i in range(start, len(urls)):
            drug = urls[i]
            print('\n{} drugs left to scrape.'.format(len(urls) - i))
            print('Scraping {}...'.format(drug['name']))
            reviews = scraper.scrape(drug['url'])

            # If it's the first drug then replace self.reviews instead of appending
            if drug['name'] == urls[0]['name']:
                self.reviews = reviews
            else:
                self.reviews += reviews

            # Save our progress and let the user know the data is safe
            self.meta['endTimestamp'] = time()
            self.save()
            print('{} reviews saved. Safe to quit.'.format(drug['name']))

            # Let the user know what start index to use to continue later
            if i < len(urls) - 1:
                print('To continue run with parameter start={}'.format(i + 1))

        print('\nAll urls scraped!')
示例#24
0
def test_drugs_max_pages():
    """Test drugs.com max pages"""
    input_url = 'https://www.drugs.com/comments/dabigatran/'
    drugs_scraper = DrugsScraper()
    assert drugs_scraper.max_pages(input_url) > 1