I just finished a scraper in python using scrapy. The scraper logs in to a certain page and then scrapes a list of other pages using the authenticated session. It retrieves the title of these pages and puts it in a list of items together with the page name.
Because there are little examples to find on continuing scraping after log-in I would like to receive some feedback on if this is the best way to continue scraping.
(Also I have a weird workaround to get the pagename into the itemlist, since I already have the pagename in the pagelist, but in the action method I retrieve it from the url again. Tips on doing this in an easier way are welcome too.)
p.s. The code has been slightly edited for sharing purposes.
class ShareSpider(scrapy.Spider):
name = "sharespider"
start_urls = ['http://www.example.com/public/login.aspx']
def parse(self, response):
yield scrapy.FormRequest.from_response(
response,
formxpath='//form[@id="login"]',
formdata={
'UserName': 'UserNameHere',
'Password': 'PasswordHere',
'Action':'1',
},
callback=self.after_login
)
def after_login(self, response):
baseurl = 'http://www.example.com/public/'
#Specify pages to crawl here:
pagelist = ['page1.aspx', 'page2.aspx', 'page3.aspx', 'page4.aspx']
for page in pagelist:
yield Request(url= baseurl + page + "?id=1",
callback=self.action)
def action(self, response):
pageurl = str(response.url)
page = re.search('public/(.*)id=1', pageurl)
if page:
pagename = page.group(1)
#Get page <title> element and strip whitespace
title = str(response.selector.xpath('//title/text()').extract_first())
res = title.strip()
item = PageItem()
item['pagename'] = pagename
item['description'] = res
yield item
callback=self.after_login
) have? \$\endgroup\$