1

この機能を完全に単純化するモジュールがあることは承知していますが、Python の基本インストール (標準モジュールのみ) から実行していると言うと、次をどのように抽出すればよいでしょうか。

リストがあります。このリストは、Web ページの行ごとのコンテンツです。以下は、情報提供を目的としたモックアップ リスト (書式なし) です。

<script>
    link = "/scripts/playlists/1/" + a.id + "/0-5417069212.asx";
<script>

"<a href="/apps/audio/?feedId=11065"><span class="px13">Eastern Metro Area Fire</span>"

上記の文字列から、次を抽出する必要があります。上記のコードでは、"/scripts/playlists/1/" および "/0-5417069212.asx" の feedId (11065) は偶然にも a.id です。これらの各行は、リスト内のオブジェクトの内容にすぎないことを思い出してください。そのデータを抽出するにはどうすればよいでしょうか?

完全なリストは次のとおりです。

contents = urllib2.urlopen("http://www.radioreference.com/apps/audio/?ctid=5586")

擬似:

from urllib2 import urlopen as getpage
page_contents = getpage("http://www.radioreference.com/apps/audio/?ctid=5586")

feedID        = % in (page_contents.search() for "/apps/audio/?feedId=%")
titleID       = % in (page_contents.search() for "<span class="px13">%</span>")
playlistID    = % in (page_contents.search() for "link = "%" + a.id + "*.asx";")
asxID         = * in (page_contents.search() for "link = "*" + a.id + "%.asx";")

streamURL     = "http://www.radioreference.com/" + playlistID + feedID + asxID + ".asx"

streamURL が = になるようにフォーマットする予定です。

http://www.radioreference.com/scripts/playlists/1/11065/0-5417067072.asx
4

1 に答える 1

0

これを正規表現で行います。Pythonのreモジュールは素晴らしいです!

ただし、ページのすべてのテキストを保持する単一の文字列を検索する方が (1 行ずつ検索を繰り返すよりも) 簡単 (かつ高速) です。可能であれば、 (またはファイル オブジェクトを直接反復処理するのread()ではなく) URL を開いたときに取得するファイルのようなオブジェクトに対してa を実行します。readlines()それができない場合は、 を使用"\n".join(list_of_strings)して行を 1 つの文字列に戻すことができます。

あなたのサンプルURLで私のために働くコードは次のとおりです。

from urllib2 import urlopen
import re

contents = urlopen("http://www.radioreference.com/apps/audio/?ctid=5586").read()

playlist_pattern = r'link = "([^"]+)" \+ a.id \+ "([^"]+\.asx)'
feed_pattern = r'href="/apps/audio/\?feedId=(\d+)"><span class="px13">([^<]+)'
pattern = playlist_pattern + ".*" + feed_pattern

playlist, asx, feed, title = re.search(pattern, contents, re.DOTALL).groups()

streamURL = "http://www.radioreference.com" + playlist + feed + asx

print title
print streamURL

出力:

Eastern Metro Area Fire
http://www.radioreference.com/scripts/playlists/1/11065/0-5417090148.asx

すべてのマッチングを 1 回のパスで行う必要は厳密にはありません。必要に応じて、 と を使用playlist_patternfeed_patternてそれぞれ 2 つのパーツを取得できます。ただし、一部のピースに対して余分な一致が発生し始めるため、半分のいずれかを分割するのは少し難しくなります (たとえば、いくつかの同一link = "stuff"のセクションがあります)。

于 2012-11-30T11:02:25.193 に答える