【问题标题】:Beautiful Soup in DjangoDjango中的美丽汤
【发布时间】:2013-09-24 12:04:42
【问题描述】:

我有这段代码,我需要从表中的每个 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 } )

【问题讨论】:

    标签: python django beautifulsoup


    【解决方案1】:

    试试这个:

    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 的数组。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-15
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 1970-01-01
      • 1970-01-01
      • 2010-10-27
      相关资源
      最近更新 更多