I wrote this code in Python/ Scrapy for data extraction. It works fine for me, but I am a newbie in Python, so any suggestions for code optimization would be welcome.
def parse(self, response):
hxs = HtmlXPathSelector(response)
item = GenesishcsItem()
item['graduate_education']=[]
item['medical_school']=[]
item['specialty']=[]
item['name']=ParseUtils.get_line_from_node(hxs.select(".//*[@id='DrDetail']//div[@class='Designations']/h1"))
image_url=hxs.select("//img[contains(@id,'DoctorProfilePicture')]/@src").extract()
if image_url:
item['image_url']=urljoin(response.request.meta['cached_meta']['response_url'],image_url[0])
for key,value in {'Gender:':'gender','Year joined staff:':'year_joined_staff'}.iteritems():
result=ParseUtils.get_line_from_node(hxs.select("//dt[contains(.,'%s')]/following-sibling::dd"%key))
if result:
item[value]=result
edu_data=['Education','Residency','Fellowship','Internships']
for edu in edu_data:
result_date=hxs.select("//h4[contains(.,'%s')]/following-sibling::dl[@class='%s']/dt"%(edu,edu))
result=hxs.select("//h4[contains(.,'%s')]/following-sibling::dl[@class='%s']/dd"%(edu,edu))
for date,value in zip(result_date,result):
date=date.select('./text()').extract()
value=value.select('./text()').extract()
if date:
date=date[0]
else:
date=None
if value:
value=value[0]
else:
value=None
if 'Education' in edu:
pass
item['medical_school'].append({'name':value,'graduation_year':date})
else:
item['graduate_education'].append({'name':value,'start_year_end_year':date,'type':edu.lower().strip()})
for rs in ParseUtils.get_text_from_node(hxs.select("//h3[contains(.,'Board Certified')]/following-sibling::p")):
item['specialty'].append({'name':rs,'certified':True})
return item