User:Ifeanyi liam/Outreachy 4
Jump to navigation
Jump to search
Code for task 4
[edit]import pywikibot as pw from datetime import date class wd_update: site = pw.Site('en', 'wikipedia') wk_data = pw.Site('wikidata', 'wikidata') repo = wk_data.data_repository() def __init__(self, pg_name, wk_db): self.page = pw.Page(self.site, pg_name) self.wk_db = wk_db self.wk_item = pw.ItemPage(self.repo, self.wk_db) self.clm_obj = self.wk_item.get().get('claims') def add_qid(self, prop, qid): if prop not in self.clm_obj: new_claim = pw.Claim(self.repo, prop) target = pw.ItemPage(self.repo, qid) new_claim.setTarget(target) self.wk_item.addClaim(new_claim, summary=f'adding claim {prop} to item') print('Done') else: print(f"{prop} already exist") def add_image(self, img_prop): prop = self.page.properties().get('page_image_free') # check if the property is in the claim item if img_prop not in self.clm_obj: if not prop: raise FileNotFoundError('Image File does not exist') # create a link for the image property commonssite = pw.Site('commons', 'commons') imagelink = pw.Link(prop, source=commonssite, default_namespace=6) image = pw.FilePage(imagelink) # to get the image link as a redirected webpage if image.isRedirectPage(): image = pw.FilePage(image.getRedirectTarget()) # save the image item to the wikidata item new_claim = pw.Claim(self.repo, img_prop) new_claim.setTarget(image) self.wk_item.addClaim(new_claim, summary='add new image') print('Done') else: print(f"{img_prop} already exist") def add_num(self): pass def add_date(self, birthday, prop): if birthday is not None: my_bd = date.fromisoformat(birthday) if prop not in self.clm_obj: dateclaim = pw.Claim(self.repo, prop) birthd = pw.WbTime(year=my_bd.year, month=my_bd.month, day=my_bd.day) dateclaim.setTarget(birthd) self.wk_item.addClaim(dateclaim, summary='Adding dateOfBirth') def main(): duh = wd_update('Igbo-Ukwu', 'Q4115189') dateOfBirth = '1993-05-03' duh.add_date(dateOfBirth, 'P569') duh.add_image('P18') duh.add_qid('P17', 'Q1033') if __name__=="__main__": main()