【发布时间】:2016-08-11 13:59:49
【问题描述】:
作为初学者,我们正忙于使用 python 中的抓取工具。它几乎完成了,但现在我们想要一个 JSON 文件中的结果。我们试过了,但它不起作用。有没有代码英雄可以帮助我们?
from bs4 import BeautifulSoup
import urllib
jaren = [str("2010"), str("2012")]
DESIRED_COLUMNS = {1, 2, 5} # it is a set
for Jaargetal in jaren:
r = urllib.urlopen("http://www.nlverkiezingen.com/TK" + Jaargetal +".html").read()
soup = BeautifulSoup(r, "html.parser")
tables = soup.find_all("table")
for table in tables:
header = soup.find_all("h1")[0].getText()
print header
trs = table.find_all("tr")[0].getText()
print '\n'
for tr in table.find_all("tr")[:22]:
print "|".join([x.get_text().replace('\n', '')
for index, x in enumerate(tr.find_all('td'))
if index in DESIRED_COLUMNS])
【问题讨论】:
-
这是您的实际代码吗?因为你现在有语法和缩进问题。
-
@idjaw 我已经更新了代码。现在没有错误了。
-
您仍然有缩进问题。特别是
r = urllib.urlopen("http://www.nlverkiezingen.com/TK" + Jaargetal +".html").read()。那个for循环应该是什么?for Jaargetal in jaren下面的所有内容都应该在那个循环内吗?你应该确保你的代码是你正在运行的代码的精确表示 -
对不起,现在代码应该可以工作了。里面有一些尝试的东西。
-
请仔细看代码。它仍然没有正确缩进。看看
for Jaargetal in jaren:。代码没有在该行下方缩进。