Last week, someone reminded me of an old project I had on GitHub that scraped fantasy football stats from Yahoo. Unfortunately, it was antiquated and failed to retrieve the data for the current season. I’ve also been interested in trying out the Scrapy framework and decided this would be a good opportunity to give it a shot. I tried finding a sample project that dealt with authentication as a starting point but wasn’t able to find one so hopefully my attempt can serve as an example to others.
parse method: This submits a form POST to the Yahoo login page which authenticates the session. The key point here is to specify a callback function which will continue the existing session.
parse_stats method: In previous projects, I struggled with separating the crawling from the parsing since the page would have information that would relevant to both - for example I would want to extract information from a page as well as find the next page to scrape. Scrapy offers a nice solution by letting you return different types from the same method. Returing a Request will lead to another page being crawled but one can also returned the scraped structured data via an Item. In the case of the scraper, I return the fantasy football stats on each page via Items but also return a Request when I want to navigate to the next page of stats.
XPath expressions: In the past, I'd use either BeautifulSoup or PyQuery to traverse the DOM but found XPath expressions to be simpler. There’s less code to write and the expressions are easier to understand and have a higher information density.
This also got me thinking about the evolution of my approach to scraping. In 2006, I was into Perl and scraped using the LWP::Simple, WWW::Mechanize and the HTML::TreeBuilder libraries. After I moved on to Python I switched to using urllib and BeautifulSoup. Most recently, I’ve started using the wonderful requests library along with PyQuery. Conceptually, these approaches are the same: first retrieve a web page and then extract the data you want by traversing the DOM. Scrapy does the same thing internally but by removing a ton of the boilerplate, it lets you focus on the key problems in scraping - figuring out what page to scrape next and figuring out how to extract the content. The rest is handled by Scrapy itself - including file storage, retries, throttling, and probably a ton more that I haven’t gotten a chance to explore yet.
This also gives me some time to work on the actual draft algorithm. My goal is to create a strategy that’s using a value based approach combined with my schedule. The idea is that I shouldn’t pick the players that will have the highest point total over the season but the ones that will have more points during my tough matchups. Of course, it’s almost all luck but I’m still looking forward to attempting this approach.