Skip to content

Instantly share code, notes, and snippets.

@umihico
Last active July 11, 2018 02:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umihico/107d38fa06ef01810d3059c587ad039c to your computer and use it in GitHub Desktop.
Save umihico/107d38fa06ef01810d3059c587ad039c to your computer and use it in GitHub Desktop.
wikipedia単ページのスクレイピング
def get_info_wikipedia(lxml_htmltree):
result = {}
title = lxml_htmltree.xpath(
"//h1[@id='firstHeading']")[0].text_content()
result = {"title": title}
result.update(_get_righttop_infobar(lxml_htmltree))
return result
def _get_righttop_infobar(lxml_htmltree):
tables = lxml_htmltree.xpath("//table[@class='infobox']")
# if len(tables) > 1:
# raise Exception(f"xpath detected {len(tables)} elements.")
try:
caption = tables[0].xpath(".//caption")[0].text
english_caption = tables[0].xpath(".//caption//span")[0].text_content()
except (Exception, ) as e:
caption = ""
english_caption = ""
result = {"caption": caption, "english_caption": english_caption}
for tr in tables[0].xpath(".//tr"):
ths = tr.xpath(".//th")
tds = tr.xpath(".//td")
if len(ths) > 0 and len(tds) > 0:
th_text = ' '.join([th.text_content() for th in ths])
td_text = ' '.join([td.text_content() for td in tds])
result[_strip_text(th_text)] = _strip_text(td_text)
return result
def _strip_text(text):
while True:
if text.startswith('\n'):
text = text[1:]
else:
break
return text
if __name__ == '__main__':
from codecs import open
from pprint import pformat
from lxml import html
import requests
res = requests.get('https://ja.wikipedia.org/wiki/EIZO')
lxml_htmltree = html.fromstring(res.text)
result = get_info_wikipedia(lxml_htmltree)
with open("result.txt", 'w', 'utf-8') as f:
f.write(pformat(result))
{'caption': 'EIZO株式会社',
'english_caption': 'EIZO Corporation',
'title': 'EIZO',
'主要子会社': 'アイレムソフトウェアエンジニアリング株式会社',
'主要株主': '日本トラスティ・サービス信託銀行(信託口) 3.80%北陸銀行 3.73%北國銀行 3.49%三井住友信託銀行 (信託口 '
'甲2号)3.17%村田ヒロシ 3.15%(平成28年3月31日現在)',
'事業内容': 'コンピュータ用ディスプレイ',
'代表者': '実盛祥隆(代表取締役社長)',
'営業利益': '連結50億8100万円(2016年3月期)',
'売上高': '連結748億7800万円(2016年3月期)',
'外部リンク': 'http://www.eizo.co.jp/',
'市場情報': '東証1部 6737 東証1部 6737',
'従業員数': '単体656名、連結1,829名(2016年3月)',
'本社所在地': ' 日本〒924-8566石川県白山市下柏野町153番地 北緯36度29分40.6秒 東経136度31分56.4秒\ufeff / '
'\ufeff北緯36.494611度 東経136.532333度\ufeff / 36.494611; 136.532333座標: '
'北緯36度29分40.6秒 東経136度31分56.4秒\ufeff / \ufeff北緯36.494611度 '
'東経136.532333度\ufeff / 36.494611; 136.532333',
'業種': '電気機器',
'決算期': '毎年3月31日',
'法人番号': '8220001009300',
'略称': 'EIZO',
'発行済株式総数': '22,731,160株',
'種類': '株式会社',
'純利益': '連結42億200万円(2016年3月期)',
'純資産': '連結780億1100万円(2016年3月)',
'総資産': '連結1047億9200万円(2016年3月)',
'設立': '1968年3月6日',
'資本金': '44億2574万円',
'関係する人物': '高嶋哲'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment