0

私はPythonweb.pyフレームワークを使用して小さなWebアプリを構築しています。

それはで構成されています

  1. Home pageURL を入力として受け取る
  2. 読み取りanchor textanchor tagsそれから
  3. csvファイルに書き込んでダウンロード

ここでは、ボタンをクリックするとステップ 2 と 3 が発生しexport the linksます。以下は私のコードです。

コード.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()

home.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 を受け取るテキスト ボックスを含むフォームを表示し、アンカー タグ リンクとテキストを含む csv ファイルのボタンexport the linksボタンを備えています。downloads/exports

  1. たとえば、送信http://www.google.co.inしてクリックするとexport the links、すべてのアンカー URL とアンカー テキストが csv ファイルに保存され、正常にダウンロードされます。

  2. http://stackoveflow.comただし、たとえば、すぐに他の URL を指定してexport the linksボタンをクリックすると、csv ファイル (上記のコードに示すように URL のドメイン名で作成されたもの) がタグ リンクでダウンロードされますが、ダウンロードされた csv ファイルにはデータ (アンカー) も含まれますである以前の URL のテキストとリンク) http://www.google.co.in

export classつまり、異なる URL から同じ csv ファイルでデータがオーバーライドされているということです。csv ファイルを生成する上記のコード ( ) のどこが間違っているのか、別の URL で新しい csv ファイルを作成する代わりにデータが上書きされる理由を教えてください。名前は動的に作成されますか?

最後に、新しい URL を指定するたびに URL からデータ (アンカー タグ テキストと url ) を書き込むことにより、URL のドメイン名 (私のコードでは上記のようにスライス) を含む新しい csv ファイルをダウンロード/エクスポートすることを意図しています。 .

上記のコードを拡張/必要な変更を加えて、個々のURLの個別のcsvファイルをダウンロードしてください........

4

0 に答える 0