0

我有这段代码,我需要从表中的每个 tr 标签移动并在 6 个 td 标签中打印数据,然后移动到下一个 tr 标签,直到所有 tr 标签都被访问。我正在使用美丽的汤 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 } )
4

1 回答 1

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

结果是切片 trs 的数组。

于 2013-09-24T13:43:09.040 回答