通常,要解决此类问题,您必须首先将感兴趣的页面下载为文本(使用或其他任何东西,甚至是 curl 或 wget 等外部实用程序,但不是浏览器,因为您想在任何 Javascript之前urllib.urlopen
查看页面的外观)运行的机会)并研究它以了解其结构。在这种情况下,经过一番研究,您会发现相关部分是(剪掉一些不相关的部分并打破线条以提高可读性)......: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>
因此,您希望将 a 中标签的内容作为“主题” <dt>
,并将其后的标签内容作为“内容” <dd>
(在同一 中<dl>
)。
您获得的标题包含:
Content-Type: text/html; charset=ks_c_5601-1987
因此,您还必须找到一种将编码解释为 Unicode 的方法——我相信编码也被称为'euc_kr'
并且我的 Python 安装似乎带有它的编解码器,但你也应该检查你的。
一旦你确定了所有这些方面,你就可以尝试lxml.etree.parse
URL——而且,就像许多其他网页一样,它不会解析——它并没有真正呈现格式良好的 HTML(尝试 w3c 的验证器来了解它的一些损坏方式)。
由于格式错误的 HTML 在 Web 上如此普遍,因此存在试图弥补常见错误的“容错解析器”。Python中最流行的是BeautifulSoup,并且确实带有lxml——在lxml 2.0.3或更高版本中,你可以使用BeautifulSoup作为底层解析器,然后“就像”文档已经正确解析一样——但我发现直接使用 BeautifulSoup 更简单。
例如,这是一个脚本,用于在该 URL 处发出前几个主题/内容对(它们当前已更改,最初它们与您提供的相同;-)。您需要一个支持 Unicode 输出的终端(例如,我在 Mac 的 Terminal.App 设置为 utf-8 上运行它没有问题)——当然,print
您可以收集 Unicode 片段而不是 s(例如将它们附加到一个列表和''.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”,并没有太大的不同,只是各种导航操作的拼写和大小写略有变化。