Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/tfs/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python BeatifulSoup:我可以打印出整个表,但它只能将表中的一行保存到*.html文件中_Python - Fatal编程技术网

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

Python BeatifulSoup:我可以打印出整个表,但它只能将表中的一行保存到*.html文件中,python,Python,这是我的密码: from bs4 import BeautifulSoup import urllib2 import codecs import json def results(**kwargs): """parse and save the data""" url = 'http://www.sailwx.info/shiptrack/shipposition.phtml?call=wrn5495' web = BeautifulSoup(urllib2.urlo

这是我的密码:

from bs4 import BeautifulSoup
import urllib2
import codecs
import json

def results(**kwargs):
    """parse and save the data"""
    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 = codecs.open('AIS_Page.html', 'w', 'utf-8') 
        AIS.write(coordinates)
        AIS.close()

if __name__ == '__main__':
    results()
    print 'Saved parsed data'

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

您一直使用
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)

你到底想做什么?你的问题是什么?我最终想制作一个本地主机网络地图。因此,我从上面的url中提取整个表,将其保存到一个*.html和*.json文件并映射它。谢谢!作为一名python新手,我很困惑,如果在学期中打印出来,为什么它不会保存到html中。再次感谢!别担心,这是很容易犯的错误。