BeatifulSoup:我可以打印出整个表格,但只将表格的一行保存到* .html文件中

时间:2015-04-30 16:42:23

标签: python

这是我的代码:

Mage_Catalog_Model_Layer

我可以在打印时看到所有行,但我的代码只将一行保存到我的文件中。

1 个答案:

答案 0 :(得分:2)

您继续使用w进行覆盖,因此您只能看到最后一个值,您需要使用a进行追加:

 AIS = codecs.open('AIS_Page.html', 'a', 'utf-8') 

或者更聪明的方法是在循环外打开一次:

def results(**kwargs):
    """parse and save the data"""
    with codecs.open('AIS_Page.html', 'w', 'utf-8')  as AIS:
        url = 'http://www.sailwx.info/shiptrack/shipposition.phtml?call=wrn5495'
        web = BeautifulSoup(urllib2.urlopen(url).read())
        for tr in web.find_all ('tr')[4:142]:
            tds = tr.find_all('td')
            coordinates = ("Date/time: %s, Position: %s, Speed:%s" %\         (tds[0].text,tds[1].text, tds[3].text))
            AIS.write(coordinates)