Django美丽的汤

时间:2013-09-24 12:04:43

标签: python django beautifulsoup

我有这个代码我需要从表中的每个tr标签移动并以6 td标签打印数据并移动到下一个tr标签,直到所有tr标签都被访问。我正在使用Beautiful Soup 4。

from django.shortcuts import render
from bs4 import BeautifulSoup
import urllib
import re

def home(request):
    url = urllib.urlopen("http://etrain.info/in?STATION=SME#!TRAIN_BETWEEN=SMET-MYS")
    soup = BeautifulSoup(url) 
    #soup.body.name
    #soup.body.string
    #soup.get_text()
    #st = soup.td.string
    #st1 = soup.td.string
    my_string = b"\n"

    #tag2 = b'st1'
    #tag2_u = st1
    #ta = soup.find('table')
    #tag=soup.findAll('title')
    #tag_a=tag[0].find('title')
    table = soup.find( "table", {"class":"myTable nocps"} )
    tag1 =' '
    tag4 =' '
    tag2 = table.find_all("td")
    length=len(tag2)
    for row in range(0,6): 
         tag1 +="    "
         tag1 += tag2[row].text
    for row in range(22,29): 
         tag4 +=" "
         tag4 += tag2[row].text  





    #tag4 = tag2[0].text

    return render(request, "base.html", {'hello': tag1,'hell' :tag4 } )

1 个答案:

答案 0 :(得分:0)

试试这个:

result = []
trs = table.findAll("tr")
for tr in trs:
   tds = tr.findAll('td')
   _res = []
   for i in range (0, 6):
       _res.append(tds[i].text)
   result.append(_res)
print result

结果是你的切片的数组。

相关问题