我知道有些模块完全简化了这个功能,但是说我是从python的基础安装(仅限标准模块)运行的,我将如何提取以下内容:
我有一份清单。该列表是网页的逐行内容。这是一个模拟列表(未格式化),用于提供信息:
<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>"
从上面的字符串中,我需要提取以下内容。 feedId(11065),在上面的代码中偶然是a.id,“/ scripts / playlists / 1 /”和“/0-5417069212.asx”。记住这些行中的每一行都只是列表中对象的内容,我将如何提取该数据?
以下是完整列表:
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
答案 0 :(得分:0)
我是用正则表达式做的。 Python的re
模块很棒!
但是,搜索包含所有页面文本的单个字符串(而不是逐行重复搜索)会更容易(也更快)。如果可以,请在打开URL时获得read()
,而不是readlines()
(或直接遍历文件对象)。如果你不能这样做,你可以使用"\n".join(list_of_strings)
将行重新放回一个字符串。
以下是一些适用于您的示例网址的代码:
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
一次性完成所有匹配并非绝对必要。如果需要,您可以使用playlist_pattern
和feed_pattern
分别获得两个部分。尽管如此,将两半中的任何一个分开是有点困难,因为你将开始为某些部分运行额外的匹配(例如,有几个相同的link = "stuff"
部分。)