我試圖抓取一些網頁內容,而且我很難格式化輸出。我的代碼生成一個列表,然後迭代該列表以添加更多信息。我收到了我需要的所有數據,但是當我嘗試將它保存爲CSV時,我每行都得到了多個列表。我不知道如何完成這一點。在Python中對列表進行格式化
這裏是我的代碼:
def getPeople(company, url, filename):
persList = []
category = os.path.splitext(filename)[0]
code = urllib.urlopen(url)
html = code.read()
unic = unicode(html, errors='ignore')
tree = etree.parse(StringIO(unic), parser)
personNames = tree.xpath('//a[@class="person"]/text()')
personUrls = tree.xpath('//a[@class="person"]/@href')
for i, j in zip(personNames, personUrls):
personInfo = (company, category, i, j)
internal = list(personInfo)
persList.append(internal)
result = list(persList)
return result
def tasker(filename):
peopleList = []
companyNames = getCompanies(filename, '//a[@class="company"]/text()')
companyUrls = getCompanies(filename, '//a[@class="company"]/@href')
for i, j in zip(companyNames, companyUrls):
peopleLinks = getPeople(i, j, filename)
internal = list(peopleLinks)
peopleList.append(internal)
output = csv.writer(open("test.csv", "wb"))
for row in itertools.izip_longest(*peopleList):
output.writerow(row)
return peopleList
下面是輸出的一個樣本:
[[['3M', 'USA', 'Rod Thomas', 'http://site.com/ron-thomas'], ['HP', 'USA', 'Todd Gack', 'http://site.com/todd-gack'], ['Dell', 'USA', 'Phil Watters', 'http://site.com/philwatt-1'], ['IBM', 'USA', 'Mary Sweeney', 'http://site.com/ms2105']], [['3M', 'USA', 'Tom Hill', 'http://site.com/tomhill'], None, ['Dell', 'USA', 'Howard Duck', 'http://site.com/howard-duck'], None], [['3M', 'USA', 'Neil Rallis', 'http://site.com/nrallis-4'], None, None, None]]
這使得一個醜陋的CSV文件,該文件難以閱讀。任何人都可以將我指向正確的方向嗎?編輯: 這是我想輸出看起來像。
[['3M', 'USA', 'Rod Thomas', 'http://site.com/ron-thomas'], ['HP', 'USA', 'Todd Gack', 'http://site.com/todd-gack'], ['Dell', 'USA', 'Phil Watters', 'http://site.com/philwatt-1'], ['IBM', 'USA', 'Mary Sweeney', 'http://site.com/ms2105'], ['3M', 'USA', 'Tom Hill', 'http://site.com/tomhill'], ['Dell', 'USA', 'Howard Duck', 'http://site.com/howard-duck'], ['3M', 'USA', 'Neil Rallis', 'http://site.com/nrallis-4']]
能否請您發表您想要的格式是什麼? – PearsonArtPhoto
好問題。我只是更新了問題以包含我希望看到的輸出。 – Lenwood
一般來說,對於這種類型的任務,您希望將用於瀏覽網站的代碼與您的邏輯分開。編寫函數,適當地命名它們,然後它們從控制邏輯的函數中調用它們。 – kreativitea