你有一個原子飼料在那裏,所以我會用feedparser
來處理:
import feedparser
result = feedparser.parse('https://gdata.youtube.com/feeds/api/videos/Ej4_G-E1cAM/comments')
for entry in result.entries:
print entry.author
此打印:
FreebieFM
micromicros
FreebieFM
Sarah Grimstone
FreebieFM
# etc.
Feedparser是一個外部庫,但很容易安裝。如果您只需要使用標準庫,則可以使用ElementTree
API,但要解析Atom提要,您需要將HTML實體包含在解析器中,並且必須處理名稱空間(而不是ElementTree
的優點):
from urllib2 import urlopen
from xml.etree import ElementTree
response = urlopen('https://gdata.youtube.com/feeds/api/videos/Ej4_G-E1cAM/comments')
tree = ElementTree.parse(response)
nsmap = {'a': 'http://www.w3.org/2005/Atom'}
for author in tree.findall('.//a:author/a:name', namespaces=nsmap):
print author.text
的nsmap
字典讓ElementTree
的a:
前綴轉化爲正確的命名空間的元素。
感謝編輯後cfreak,我是一個新的! – Freebie 2013-04-04 16:15:10
沒問題。歡迎來到Stackoverflow。你可以做的另一件事是添加你迄今爲止嘗試過的代碼。爲了讓它看起來像我讓你的XML只是突出顯示它,並點擊小按鈕(或者把它放在它周圍)。 – Cfreak 2013-04-04 16:16:43
你可以在Python中使用一個名爲beautifulsoup的工具。這將滿足您所有的HTML解析需求。我不會推薦除python以外的任何東西:) – karthikr 2013-04-04 16:16:56