从python脚本编写Json文件

2024-10-02 14:26:09 发布

您现在位置:Python中文网/ 问答频道 /正文

作为初学者,我们正忙于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])

Tags: columnsinimportfortableallfindurllib