一般来说,要解决这些问题,您必须首先下载感兴趣的页面作为文本(使用urllib.urlopen
或其他任何东西,甚至是外部实用工具,如curl或wget,但不是浏览器,因为您想查看页面的外观之前任何Javascript都有机会运行)并研究它以了解其结构。在这种情况下,一些研究之后,你会发现相关的部分(在head
剪断一些无关紧要的零部件,打破排队的可读性)...:
<body onload=nx_init();>
<dl>
<dt>
<a href="http://news.naver.com/main/read.nhn?mode=LSD&mid=sec&sid1=&oid=091&aid=0002497340"
[[snipping other attributes of this tag]]>
JAPAN TOKYO INTERNATIONAL FILM FESTIVAL</a>
</dt>
<dd class="txt_inline">
EPA¿¬ÇÕ´º½º ¼¼°è <span class="bar">
|</span>
2009.10.25 (ÀÏ) ¿ÀÈÄ 7:21</dd>
<dd class="sh_news_passage">
Japan, 25 October 2009. Gayet won the Best Actress Award for her role in the film 'Eight <b>
Times</b>
Up' directed by French filmmaker Xabi Molia. EPA/DAI KUROKAWA</dd>
等等。因此,您需要将<a>
标签的内容作为“主题”在<dt>
之内,并将其作为“内容”后面的<dd>
标签的内容(在同一<dl>
中)。
你得到的报头包含:
Content-Type: text/html; charset=ks_c_5601-1987
所以你也必须找到一种方法来解释编码转换成Unicode - 我相信,编码也被称为'euc_kr'
和我的Python安装似乎来了编解码器,但你也应该检查你的。
一旦你确定了所有这些方面,你就会尝试lxml.etree.parse
这个URL--就像很多其他网页一样,它不会解析 - 它并不真正呈现格式良好的HTML(尝试w3c的验证器可以找出它被破坏的一些方法)。
由于格式错误的HTML在网络上非常普遍,因此存在一些“宽容的解析器”,它们试图弥补常见的错误。在Python中最受欢迎的是BeautifulSoup,事实上lxml也带有它 - 使用lxml 2.0.3或更高版本,可以使用BeautifulSoup作为底层解析器,然后继续“就好像”文档已经正确解析 - 但是我发现直接使用BeautifulSoup更简单。
例如,下面是一个脚本,用于在该URL发出前几个主题/内容对(它们当前已更改,原本它们与您给出的相同;-)。您需要一个支持Unicode输出的终端(例如,我可以在Mac的Terminal.App中设置为utf-8的情况下运行此功能) - 当然,您也可以收集Unicode片段(例如追加它们到列表和''.join
他们当你拥有所有必需的部件),它们编码只要你愿意等,等
from BeautifulSoup import BeautifulSoup
import urllib
def getit(pagetext, howmany=0):
soup = BeautifulSoup(pagetext)
results = []
dls = soup.findAll('dl')
for adl in dls:
thedt = adl.dt
while thedt:
thea = thedt.a
if thea:
print 'SUBJECT:', thea.string
thedd = thedt.findNextSibling('dd')
if thedd:
print 'CONTENT:',
while thedd:
for x in thedd.findAll(text=True):
print x,
thedd = thedd.findNextSibling('dd')
print
howmany -= 1
if not howmany: return
print
thedt = thedt.findNextSibling('dt')
theurl = ('http://news.search.naver.com/search.naver?'
'sm=tab%5Fhty&where=news&query=times&x=0&y=0')
thepage = urllib.urlopen(theurl).read()
getit(thepage, 3)
的逻辑LXML或“BeautifulSoup在LXML衣”,是不是很不同,只是各种导航操作的拼写和大小有所变化。
您能向我们展示您的尝试,以便我们可以看到您遇到问题的位置吗? – Mark 2009-10-25 17:30:37
对于迟到的回复感到抱歉,这里是凌晨。 :) 我附上了我的废料源在pastebin网站。 http://elca.pastebin.com/m52e7d8e0 目前有一些probelm,非常感谢 – paul 2009-10-25 22:42:06