我正在使用Pythonweb.py
构建小型网络应用程序的框架。
它由一个
-
Home page
以 url 作为输入
- Reads
anchor text
and anchor tags
从中
- 将其写入 csv 文件并下载
当我们点击 a 时,就会发生步骤 2 和 3export the links
按钮,下面是我的代码
code.py
import web
from web import form
import urlparse
from urlparse import urlparse as ue
import urllib2
from BeautifulSoup import BeautifulSoup
import csv
from cStringIO import StringIO
urls = (
'/', 'index',
'/export', 'export',
)
app = web.application(urls, globals())
render = web.template.render('templates/')
class index:
def GET(self):
return render.home()
class export:
def GET(self):
i = web.input()
if i.has_key('url') and i['url'] !='':
url = i['url']
page = urllib2.urlopen(url)
html = page.read()
page.close()
decoded = ue(url).hostname
if decoded.startswith('www.'):
decoded = ".".join(decoded.split('.')[1:])
file_name = str(decoded.split('.')[0])
csv_file = StringIO()
csv_writer = csv.writer(csv_file)
csv_writer.writerow(['Name', 'Link'])
soup = BeautifulSoup(html)
for anchor_tag in soup.findAll('a', href=True):
csv_writer.writerow([anchor_tag.text,anchor_tag['href']])
web.header('Content-Type','text/csv')
web.header('Content-disposition', 'attachment; filename=%s.csv'%file_name)
return csv_file.getvalue()
if __name__ == "__main__":
app.run()
首页.html:
$def with()
<html>
<head>
<title>Home Page</title>
</head>
<body>
<form method="GET" action='/export'>
<input type="text" name="url" maxlength="500" />
<input class="button" type="submit" name="export the links" value="export the links" />
</form>
</body>
</html>
上面的 html 代码显示一个带有文本框的表单,该文本框接受 url ,并有按钮export the links
按钮那个downloads/exports
带有锚标记链接和文本的 csv 文件。
例如当我们提交http://www.google.co.in
然后单击export the links
,所有锚点网址和锚文本都保存到csv文件中并成功下载
但例如当我们给出其他网址时http://stackoveflow.com
立即并单击export the links
按钮,csv 文件(如上面代码所示,使用 url 的域名创建)正在使用标签 links 进行下载,但下载的 csv 文件还包含之前 url 的数据(锚文本和链接),即http://www.google.co.in
.
也就是说,数据在来自不同网址的同一个 csv 文件中被覆盖,任何人都可以让我知道上面的代码有什么问题(export class
)生成 csv 文件,为什么数据被覆盖而不是创建一个动态创建的具有不同名称的新 csv 文件?
最后,我的目的是下载/导出一个新的 csv 文件,其中包含 url 的域名(在我的代码中如上所述进行切片),每次我们给出新 url 时,都会将数据(锚标记文本和 url )从 url 写入其中。
任何人都可以扩展/对我的上述代码进行必要的更改,以下载单个 url 的单个 csv 文件.......