一般来说,要解决此类问题,您必须首先以文本形式下载感兴趣的页面(使用 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>
等等。因此,您希望将<dt> 中的<a> 标记的内容作为“主题”,并将其后面的<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 片段而不是 prints(例如将它们附加到一个列表中,当你拥有所有必需的部分时''.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中的逻辑,或者“lxml服装中的BeautifulSoup”,差别不大,只是各种导航操作的拼写和大小写有点变化。