2012-09-22 47 views
0

我在Python中使用lxml来抓取网页。然而,为了得到表格的行数,我首先得到它们,然后使用len()函数。我觉得这很浪费,有没有其他方法可以让他们的数字(动态的)进一步刮擦?lxml网页解析内容的长度

import lxml.html 
doc = '' 
try: 
    doc = lxml.html.parse('url') 
except SkipException: pass 

if doc: 
    buf = '' 
    #get the total number of rows in table 
    tr = doc.xpath("/html/body/div[1]/div[1]/table[1]/tbody/tr") 
    table = [] 
    # iterate over the table rows limited to max number 
    for i in range(3, len(tr)): 
      # get the rows content            
      table += doc.xpath("body/div[1]/div[1]/table[1]/tbody/tr[%s]/td" % i) 
+0

为什么'beautifulsoup'标签?你只在这里使用'lxml'。 –

+0

对不起,我以为可以用bs代替即兴 –

回答

0

您可以使用您为出发点匹配tr元素,你可以简单地对他们进行迭代就像你使用Python列表:

tr = doc.xpath("/html/body/div[1]/div[1]/table[1]/tbody/tr") 
for row in tr[3:]: 
    table += row.findall('td') 

上述用途.findall()抓住所有包含td元素,但如果您需要更多控制,则可以使用更多.xpath()调用。

0
from itertools import islice 

trs = doc.xpath("/html/body/div[1]/div[1]/table[1]/tbody/tr") 
for tr in islice(trs, 3): 
    for td in tr.xpath('td'): 
     ...whatever... 
+0

为什么'islice'?不会'trs [3:]'工作吗? –

0

你尝试使用迭代方法,如本节解释说:http://lxml.de/api.html#iteration?我很确定有这样的方式。找到东西的长度,然后用(x)范围遍历它,永远不会是一个优雅的解决方案,我很确定lxml背后的人为您提供了正确的工具。