teratail header banner
teratail header banner
質問するログイン新規登録

質問編集履歴

2

追記:実行して詰まったところ

2018/02/14 15:07

投稿

teratail1111
teratail1111

スコア7

title CHANGED
File without changes
body CHANGED
@@ -21,7 +21,7 @@
21
21
  ```
22
22
  このapiの結果は以下のようになります。
23
23
  ```
24
- xxxx
24
+ xxx
25
25
  ```
26
26
 
27
27
  この結果の中から、以下の部分を取得したいと考えています。
@@ -92,4 +92,14 @@
92
92
 
93
93
  print body
94
94
  ```
95
- スクレイピングでも、XMLでもどちらでも構いませんので取得の方法を教えていただけると嬉しいです。
95
+ スクレイピングでも、XMLでもどちらでも構いませんので取得の方法を教えていただけると嬉しいです。
96
+
97
+
98
+ ### 追記
99
+ 具体的に、ElementTreeを使いtagを取得することができましたが、
100
+ ```
101
+ elem = ElementTree.fromstring(body)
102
+ print elem.tag
103
+ ```
104
+ 上記のコードを実行すると、getplayerstatusという結果は帰ってきますが、
105
+ ```<ticket>71289224:lv311038136:0:139239522:59vh8328ee4f</ticket>```の部分を取得するコードの書き方がわかりません。

1

ニコ生のapi利用について

2018/02/14 15:07

投稿

teratail1111
teratail1111

スコア7

title CHANGED
File without changes
body CHANGED
@@ -29,4 +29,67 @@
29
29
  <ticket>71289224:lv311038136:0:139239522:59vh8328ee4f</ticket>
30
30
  ```
31
31
 
32
+ ### ニコ生APIの叩き方について
33
+ ニコ生のapiはログインした状態でないとapiを叩くことができないので以下のコードでapiを叩くことができます。apiを叩くにはニコニコ生放送のアカウントが必要です。以下のコードを実行すると指定した番組idのgetplayerstatusのapi結果が帰ってきます。
34
+ ```
35
+ #!/usr/bin/python
36
+ #coding:utf-8
37
+
38
+ import sys, urllib2
39
+ import urllib
40
+ import os.path
41
+ import os
42
+ import re
43
+ import cookielib
44
+ import time
45
+ from bs4 import BeautifulSoup
46
+ import xml.etree.ElementTree as Xml
47
+ import requests
48
+ import httplib
49
+ import lxml.html
50
+ from xml.etree import ElementTree
51
+
52
+ mail = ""
53
+ password = ""
54
+
55
+ headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; ja; rv:1.9.1.5) Gecko/20091102 Firefox/3.5.5 (.NET CLR 3.5.30729)',
56
+ 'Accept': '*/*',
57
+ 'Accept-Language': 'ja,en-us;q=0.7,en;q=0.3',
58
+ 'Accept-Charset': 'UTF-8,*',
59
+ 'Connection': 'keep-alive',
60
+ 'Keep-Alive': '300',
61
+ 'Cookie': '; '}
62
+
63
+
64
+ #ログイン処理
65
+ post_dict ={'show_button_facebook':'1',
66
+ 'next_url':'',
67
+ 'mail':mail,
68
+ 'password':password
69
+ }
70
+
71
+ headers['Referer']='https://account.nicovideo.jp/'
72
+ headers['Content-type']='application/x-www-form-urlencoded';
73
+ conn = httplib.HTTPSConnection('account.nicovideo.jp')
74
+ conn.request('POST','/api/v1/login?show_button_twitter=1&site=niconico',urllib.urlencode(post_dict),headers)
75
+ rs = conn.getresponse()
76
+ mc = re.compile('(user_session=(?!deleted)[^;]*);?').search(rs.getheader('Set-Cookie'))
77
+ user_session = mc.group(1)
78
+ headers['Cookie'] = user_session
79
+ rs.read()
80
+ rs.close()
81
+ conn.close()
82
+
83
+
84
+ liveid = 'lv3{番組id}'
85
+
86
+ conn = httplib.HTTPConnection('live.nicovideo.jp', 80)
87
+ conn.request('GET', '/api/getplayerstatus/%s' % liveid, '', headers)
88
+ body = conn.getresponse().read()
89
+ rs.close()
90
+ conn.close()
91
+
92
+
93
+ print body
94
+ ```
32
95
  スクレイピングでも、XMLでもどちらでも構いませんので取得の方法を教えていただけると嬉しいです。