【发布时间】:2019-04-02 21:39:55
【问题描述】:
我正在尝试从一个网站上抓取数据,该网站包含印度所有政治人物的数据,该网站以数字表示的多个页面。
url: http://www.myneta.info/ls2014/comparisonchart.php?constituency_id=1
我希望将数据从多个网站导出为 CSV 文件。
这是我正在尝试的示例表:
<tr>
<td class=chartcell><a href='http://myneta.info/ls2014/candidate.php?candidate_id=7678' target=_blank>Banka Sahadev</a></td>
<td class=chartcell align=center>53</td>
<td class=chartcell align=center>M</td>
<td class=chartcell align=center>IND</td>
<td class=chartcell align=center><span style='font-size:150%;color:red'><b>Yes</b></span></td>
<td class=chartcell align=center><span style='font-size:160%;'><b>1</b></span></td>
<td class=chartcell align=center>1</td>
<td class=chartcell align=left> <b><span style='color:red'> criminal intimidation(506)</span></b>, <b><span style='color:red'> public nuisance in cases not otherwise provided for(290)</span></b>, <b><span style='color:red'> voluntarily causing hurt(323)</span></b>, </td>
<td class=chartcell align=center>Graduate</td>
<td class=chartcell align=center>19,000<br><span style='font-size:70%;color:brown'>~ 19 Thou+</span></td>
<td class=chartcell align=center>3,74,000<br><span style='font-size:70%;color:brown'>~ 3 Lacs+</span></td>
<td class=chartcell align=center>3,93,000<br><span style='font-size:70%;color:brown'>~ 3 Lacs+</span></td>
<td class=chartcell align=center>0<br><span style='font-size:70%;color:brown'>~ </span></td>
<td class=chartcell align=center>N</td>
<!--<td class=chartcell align=center>0<br><span style='font-size:70%;color:brown'>~ </span></td>
<td class=chartcell align=center>0<br><span style='font-size:70%;color:brown'>~ </span></td>
<td class=chartcell align=center>2,00,000<br><span style='font-size:70%;color:brown'>~ 2 Lacs+</span></td> -->
</tr>
我使用 BeautifulSoup 来获取数据,但是如果我打开 CSV 数据,它们会以某种方式合并数据并且看起来非常笨拙。
这是我的代码:
num = 1
url ='http://www.myneta.info/ls2014/comparisonchart.php?
constituency_id={}'.format(num)
headers= {'User-Agent': 'Mozilla/5.0'}
with open ('newstats.csv', 'w') as r:
r.write('POLITICIANS ALL\n')
while num < 3:
url ='http://www.myneta.info/ls2014/comparisonchart.php?
constituency_id={}'.format(num)
time.sleep(1)
response = requests.get(url, headers)
if response.status_code == 200:
soup = BeautifulSoup(response.content, 'html.parser')
tablenew = soup.find_all('table', id = "table1")
if len(tablenew) < 2:
tablenew = tablenew[0]
with open ('newstats.csv', 'a') as r:
for row in tablenew.find_all('tr'):
for cell in row.find_all('td'):
r.write(cell.text.ljust(250))
r.write('\n')
else: print('Too many tables')
else:
print('No response')
print(num)
num += 1
另外,我怎么能省略特定 td 中的数据? 就我而言,我不希望表格中的 IPC 详细信息的数据。
我对编码和 python 还很陌生。
【问题讨论】:
标签: python web-scraping html-table beautifulsoup export-to-csv