How to scrape websites filtering by its keywords in metadata?
05:00 16 Dec 2014

I have writen a scraper which is suposed to scrape only websites with keywords matching the given ones. This is the code:

class MySpider(CrawlSpider):
    name = 'smm'
    allowed_domains = []
    start_urls = ['http://en.wikipedia.org/wiki/Social_media']
    rules = (
            Rule(SgmlLinkExtractor(deny=('statcounter.com/','wikipedia','play.google','books.google.com','github.com','amazon','bit.ly','wikimedia','mediawiki','creativecommons.org')), callback="parse_items", follow= True),
             )
    def parse_items(self, response):
        items = []
        #Define keywords present in metadata to scrape the webpage
        keywords = ['social media','social business','social networking','social marketing','online marketing','social selling',
            'social customer experience management','social cxm','social cem','social crm','google analytics','seo','sem',
            'digital marketing','social media manager','community manager']
        #Extract webpage keywords 
        metakeywords = response.xpath('//meta[@name="keywords"]').extract()
        #Discard empty keywords
        if metakeywords != []:
        #Compare keywords and extract if one of the defined keyboards is present in the metadata
            if (keywords in metaKW for metaKW in metakeywords):
                for link in response.xpath("//a"):
                    item = SocialMediaItem()
                    item['SourceTitle'] = link.xpath('/html/head/title').extract()
                    item['TargetTitle'] = link.xpath('text()').extract()
                    item['link'] = link.xpath('@href').extract()
                    item['webKW'] = metakeywords
                    outbound = str(link.xpath('@href').extract())
                    if 'http' in outbound:
                        items.append(item)
        return items

However, I think I am missing something, as it also scrapes websites with none of the gicen keywords. Can you help to solve this problem? Thanks!

Dani

python web-scraping scrapy