Python网页抓取

时间:2012-11-23 22:21:49

标签: python

在python中使用这个正则表达式:

pathstring = '<span class="titletext">(.*)</span>'
pathFinderTitle = re.compile(pathstring)

我的输出是:

Govt has nothing to do with former CAG official RP Singh:
Sibal</span></a></h2></div><div class="esc-lead-article-source-wrapper">
<table class="al-attribution single-line-height" cellspacing="0" cellpadding="0">
<tbody><tr><td class="al-attribution-cell source-cell">
<span class='al-attribution-source'>Times of India</span></td>
<td class="al-attribution-cell timestamp-cell">
<span class='dash-separator'>&nbsp;- </span>
<span class='al-attribution-timestamp'>&lrm;46 minutes ago&lrm;

文本查找应该首先停止“&lt; / span&gt;”。

请在此处说明错误。

4 个答案:

答案 0 :(得分:2)

.*是任何字符的贪心匹配;它会消耗尽可能多的字符。相反,请使用非贪婪版本.*?,如

pathstring = '<span class="titletext">(.*?)</span>'

答案 1 :(得分:2)

我建议使用pyquery而不是对正则表达式发疯...它基于lxml并且使用jQuery使HTML解析变得容易。

这样的事情就是你需要的一切:

doc = PyQuery(html)
doc('span.titletext').text()

你也可以使用beautifulsoup,但结果总是一样的:不要使用正则表达式来解析HTML,有一些工具可以让你的生活更轻松。

答案 2 :(得分:1)

.*将匹配</span>,因此会一直持续到最后一个。

最佳答案是:不要使用正则表达式解析html。使用lxml库(或类似的东西)。

from lxml import html

html_string = '<blah>'
tree = html.fromstring(html_string)
titles = tree.xpath("//span[@class='titletext']")
for title in titles:
    print title.text

使用正确的xml / html解析器可以节省大量时间和麻烦。如果你推出自己的解析器,你将不得不迎合格式错误的标签,评论和其他无数的东西。不要重新发明轮子。

答案 3 :(得分:0)

您也可以轻松使用BeautifulSoup,这对于做这类事情非常有用。

#using BeautifulSoup4, install by "pip install BeautifulSoup4"
from bs4 import BeautifulSoup
soup = BeautifulSoup(html)
result = soup.find('span', 'titletext')

然后result<span>titletext等级匹配。