Web コンテンツをスクレイピングしようとしていますが、出力の書式設定に苦労しています。私のコードはリストを生成し、そのリストを繰り返し処理してさらに情報を追加します。必要なすべてのデータを取得していますが、CSV に保存しようとすると、1 行に複数のリストが表示されます。これを達成する方法がわかりません。
これが私のコードです:
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']]