【发布时间】:2015-10-11 03:38:38
【问题描述】:
我使用 Beautiful Soup 从几个页面中获取特定表格,这些页面的 URL 在url.csv 中
代码:
def parse_csv(content, delimiter = ';'):
csv_data = []
for line in content.split('\n'):
csv_data.append( [x.strip() for x in line.split( delimiter )] ) # strips spaces also
return csv_data
list_url=parse_csv(open('url.csv','rU').read())
f = csv.writer(open("raw.csv", "w",encoding='utf8',newline=''))
# Write column headers as the first line
for i in range (0,len(list_url)):
url=str(list_url[i][0]) ## read URL from an array coming from an Url-CSV
page=urllib.request.urlopen(url)
soup = BeautifulSoup(page.read(),"html.parser")
restricted_webpage= soup.find( "div", {"id":"ingredients"} )
readable_restricted=str(restricted_webpage)
soup2=BeautifulSoup(readable_restricted,"html.parser")
links = soup2.find_all('td')
print(len(links))
for link in links:
i = link.find_next_sibling('td')
if getattr(i, 'name', None):
a, i = link.string, i.string
f.writerow([a, i])
我的 CSV 看起来像:
"
Cendres brutes (%)
","
7.4
" "
Cellulose brute (%)
","
1.6
" "
Fibres alimentaires (%)
","
6.6
" "
Matière grasse (%)
","
16.0
而我希望它看起来像:
Cendres brutes(%);7.4
Cellulose brute (%);1.6
Fibres Alimentaires(%);6.6
Mati̬re grasse (%);16.0
我需要它看起来像这样有两个原因:
1. 当我在 excel 中打开这样的 CSV 时,它看起来很棒。
2. 我可以使用我的 CSV 解析器(定义在第一行 parse_csv 的解析器)并处理从我的 CSV 生成的数组,就像它是 excel 上的单元格一样。单元格[x][y]。这是非常少数。
我怎样才能做到这一点?也就是说拥有我想要的那种 CSV?
【问题讨论】:
-
为了记录,文件是不分性别的。
-
谢谢。我会记住这一点的:)
-
如果您唯一的问题是空白,您是否考虑过使用str.strip() 将其删除?
-
空格和“;”或“,”某处有问题。我无法让它工作。如果我将 .strip 添加到 .string 以进行链接并且 i 在 a,i 行中写入:Name,Quantity , 的内置方法条,
标签: python csv beautifulsoup