Tag Archive for 'python'

Page 2 of 3

pyCurl获取网页问题

终于解决了这个问题,原来是我的代码中构造HTTP header的时候多了可以接受gzip压缩,支持gzip压缩的网页就下载了也不能用BeautifulSoup分析了,原来1ting.com现在支持gzip压缩了,还换了一个nProxy,多半是把ngnix的代码改了配置重新编译了~ 真是很~~

1
2
3
4
5
6
7
8
9
10
11
12
13
# Use Pycurl
def buildHeaders(browser, referer=""):
    """
    Build HTTP Headers, So we can download wma files.
    Arguments:
    - `browser`: Which browser will use
    - `referer`: Referer url
    """

    if referer != "":
        buildHeaders = ['User-Agent: ' + browser, 'Accept: text/html, application/xml;q=0.9, audio/x-ms-wma, application/xhtml+xml, image/png, gzip, x-gzip, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1', 'Accept-Language: en-us', 'Accept-Encoding: deflate, identity, *;q=0', 'Accept-Charset: iso-8859-1, utf-8, utf-16, *;q=0.1', 'Cookie: PIN=G39J3kmH2AU0SBieDgavAg==', 'Referer:' + referer]
    else:
        buildHeaders = ['User-agent: ' + browser, 'Accept: text/html, application/xml;q=0.9, audio/x-ms-wma, application/xhtml+xml, image/png, gzip, x-gzip, image/jpeg, image/gif, image/x-xbitmap, */*;q=0.1', 'Accept-Language: en-us', 'Accept-Encoding: deflate, identity, *;q=0', 'Accept-Charset: iso-8859-1, utf-8, utf-16, *;q=0.1', 'Cookie: PIN=G39J3kmH2AU0SBieDgavAg==']
    return buildHeaders
Share

Proxy and Port Mapping With Python

Use python to do tiny proxy server by example.
Continue reading ‘Proxy and Port Mapping With Python’

Share

Python 八荣八耻

以动手实践为荣 , 以只看不练为耻;
以打印日志为荣 , 以单步跟踪为耻;
以空格缩进为荣 , 以制表缩进为耻;
以单元测试为荣 , 以人工测试为耻;

以模块复用为荣 , 以复制粘贴为耻;
以多态应用为荣 , 以分支判断为耻;
以Pythonic为荣 , 以冗余拖沓为耻;
以总结分享为荣 , 以跪求其解为耻;

每日至少抽一刻钟,解答邮件列表中初学者的问题,
每周至少抽两小时,整理新学知识将体验发表/分享出去,
通过Blog/Wiki/MaiList/个人网站……
每旬至少抽四个小时, 来翻译自个儿喜爱的自由软件的文档,
每月至少抽八小时, 快乐的编程,推进自个儿的项目,
每年至少参加一次, 自由软件的活动,传播自由软件思想,
发展一名“自由人”……

只要我们每个人都坚持下去……
10年!就足以改变中国软件的整体风貌!

Share

PycURL example

Here’s a little sample of Python code demonstrating the use of PycURL, the Python interface to libcURL. It does the same thing as my cURL example. Refer to this page for a detailed list of libcurl options.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import pycurl, StringIO
# Constants
DOWNLOADED_FILE = r'C:\temp\downloaded_file.txt'
USER_AGENT = 'Mozilla/4.0 (compatible; MSIE 6.0)'
LOGIN_URL = 'http://interesting.website.com/LogIn.asp'
LOGIN_POST_DATA = 'FormField=URL%20Encoded%20Value'
DOWNLOAD_URL = 'http://interesting.website.com/do_it.asp?do=0&something=0&interesting=0'
DOWNLOAD_REFERER = 'http://interesting.website.com/referer.asp'
FILE_MODE = 'wb'

# Set up objects
dev_null = StringIO.StringIO()
slurpp = pycurl.Curl()

# Request login page
slurpp.setopt(pycurl.USERAGENT, USER_AGENT)
slurpp.setopt(pycurl.FOLLOWLOCATION, 1)
#slurpp.setopt(pycurl.AUTOREFERER, 1) # not yet implemented in pycURL
slurpp.setopt(pycurl.WRITEFUNCTION, dev_null.write)
slurpp.setopt(pycurl.COOKIEFILE, '')
slurpp.setopt(pycurl.URL, LOGIN_URL)
slurpp.perform()

# Log in to site
slurpp.setopt(pycurl.POSTFIELDS, LOGIN_POST_DATA)
slurpp.setopt(pycurl.POST, 1)
slurpp.perform()

# Download relevant data
slurpp.setopt(pycurl.HTTPGET, 1)
slurpp.setopt(pycurl.URL, DOWNLOAD_URL)
slurpp.setopt(pycurl.REFERER, DOWNLOAD_REFERER)
outfile = file(DOWNLOADED_FILE, FILE_MODE)
slurpp.setopt(pycurl.WRITEFUNCTION, outfile.write)
slurpp.perform()

# Clean up and close out
outfile.close()
dev_null.close()
slurpp.close()
Share

Python HTML 分析

google上找了下,说 Beautiful Soup 还不错。顺便转一篇关于Python的资源文章。

Python基本安装

  • http://www.python.org/ 官方标准Python开发包和支持环境,同时也是Python的官方网站;
  • http://www.activestate.com/ 集成多个有用插件的强大非官方版本,特别是针对Windows环境有不少改进;

Python文档:

  • http://www.python.org/doc/current/lib/lib.html Python库参考手册。
  • http://www.byteofpython.info/ 可以代替Tutorial使用,有中文译版的入门书籍。
  • http://diveintopython.org/ 一本比较全面易懂的入门书,中文版翻译最近进步为很及时的5.4了。
  • http://www.python.org/peps/pep-0008.html 建议采用的Python编码风格。
  • http://doc.zoomquiet.org/ 包括Python内容的一个挺全面的文档集。

Continue reading ‘Python HTML 分析’

Share

几个Python爬虫库

Share

python和web蜘蛛

这个视乎是很古老的话题了,很多项目是用C++或者java来开发,但是python却会成为我的首选,因为她可以更快,更方便在现在实现。

相关资料

Share

web.py with fastcgi on Apache

我们为您准备了这个文档来帮助您快速的使用web.py

你可以在windows平台使用putty,UNIX则需要使用SSH.
你的用户需要有使用shell的权限,这个可以在用户控制面板中进行设置
在评论页可以看到更多的信息

目录

1.架设 web.py
1.1 CGI
1.1.1 0. 开始
1.1.2 1. 安装 web.py
1.1.3 2. 安装 Flup
1.1.4 3. 使用 Apache 服务
1.1.5 4. 检查并发现错误
1.2 FCGI
1.2.1 Benchmarking
1.2.2 重启 FASTCGI
1.2.3 改进稳定性和加快启动速度

架设 web.py

CGI
如果您按照我们的步骤来,那么架设CGI将是一件十分容易的事情.在下面的示例代码中,将example.com替换成您自己映射在dreamhost的域名.

0. 开始

进入到您的web主目录.

1
cd ~/example.com

1.安装web.py

使用Subversion命令行代码工具来获取最新的web.py

1
svn co http://webpy.org/svn/trunk/web/

按照如下方式来建立一个index.cgi,这将是您的第一个web.py网页

1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python2.4
import web
urls = ('/', 'index')
class index:
   def GET(self):
       print "Hi web.py, finally we meet!"
def runfcgi_apache(func):
    web.wsgi.runfcgi(func, None)
if __name__ == "__main__":
   web.wsgi.runwsgi = runfcgi_apache
   web.run(urls, globals())

将该文件上传到web主目录后,使用如下的命令来使该文件可访问

1
chmod +x index.cgi

2.安装Flup

使用wget命令来获取最新的fcgi

1
wget http://svn.saddi.com/py-lib/trunk/fcgi.py

按照如下提示修改web/wsgi.py

1
2
3
4
5
6
7
8
9
10
--- wsgi.py     (revision 130)
+++ wsgi.py     (working copy)
@@ -13,8 +13,8 @@
   
def runfcgi(func, addr=('localhost', 8000)):
     """Runs a WSGI function as a FastCGI server."""
-    import flup.server.fcgi as flups
-    return flups.WSGIServer(func, multiplexed=True, bindAddress=addr).run()
+    import fcgi as flups
+    return flups.WSGIServer(func, multiplexed=False, bindAddress=addr).run()

(译者注:使用++的内容替换掉–的内容)

3.使用apache的服务

编辑apache的.htaccess文件来启用cgi

1
vim .htaccess

添加如下代码

1
2
3
4
5
6
7
8
Options +ExecCGI
AddHandler cgi-script .py
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.cgi/$1 [L]
</IfModule>

4.检查并发现错误
现在,你的web主目录应该是这个样子

1
2
$ ls -F ~/example.com
fcgi.py index.cgi* web/

使用你的浏览器访问http://example.com/(您自己映射在dreamhost的域名),应该就可以看到问候语.如果浏览器显示”500内部错误”,那就应该检查下错误日志.

1
tail -n 30 ~/logs/example.com/http/error.log

(译者注:上面的内容足够成功运行web.py了,下面的内容我也还没有进行,所以仅供参考)

FCGI
1.使用FastCGI架设您的域名或二级域名.假设您的域名是todo.dabase.com
2.cd; rmdir ~/todo.dabase.com
3.svn co http://svn.natalian.org/projects/todo/
4.ln -s ~/todo ~/todo.dabase.com
5.Tweak ~/todo with your mysql db (see config.py) and email stuff for errors
并不建议您在shell下进行fcgi的测试开发,因为如果fastcgi的进程开始运行后,停止或重启这个进程都是一件让人头痛的事情.您可以使用web.reloader在本地进行开发,这样,您的任何改变将立即被反应到您的web程序.

Benchmarking

ab is from the apache2-utils Debian package.
从apache2-utils Debian包中找到ab组件

1
/usr/sbin/ab -c 4 -n 300 http://todo.dabase.com/

4 concurrent connections pushing out 300 requests. If you find it too slow, considering running lighttpd on a dedicated server.
4个并发连接将产生300个请求.如果你发现它运行太慢,请考虑在一台专用服务器上运行lighttpd.

重启FastCGI进程

为了使新的代码起作用,你需要重启fcgi进程.
如下代码将会起作用

1
killall python2.4

改进稳定性和加快启动速度

1.使用http://svn.saddi.com/py-lib/trunk/fcgi.py来代替较新的flup
2.按照如下方法修改wsgi.py

1
2
3
4
5
6
7
8
9
10
--- wsgi.py     (revision 130)
+++ wsgi.py     (working copy)
@@ -13,8 +13,8 @@
   
def runfcgi(func, addr=('localhost', 8000)):
     """Runs a WSGI function as a FastCGI server."""
-    import flup.server.fcgi as flups
-    return flups.WSGIServer(func, multiplexed=True, bindAddress=addr).run()
+    import fcgi as flups
+    return flups.WSGIServer(func, multiplexed=False, bindAddress=addr).run()
Share

用python来缩放图片

Python Imaging Library (PIL) 是一个普遍使用的图片库,你需要下载安装。这里有一段示例代码,最新的代码看这里

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#!/usr/bin/env python
# $Id: thumbnails_create.py 5 2007-05-10 05:44:05Z zhuzhu $
# first you must install Python Imaging Library (PIL) at
# http://www.pythonware.com/products/pil/
import os, sys
import Image
import glob

size = [580,1024]
files = glob.glob('*.jpg')
# files = ["Leah_Dizon_613516.jpg"]

for infile in files:
    im = Image.open(infile)
    if im.size[0] > size[0]:
        how = (size[0]*100)/im.size[0]
        outfile = os.path.splitext(infile)[0] + ".webcan.jpg"
        if infile != outfile:
            try:
                im = im.resize((size[0], (im.size[1]*how)/100), Image.BILINEAR)
                im.save(outfile, "JPEG")
                print outfile+" is created"
            except IOError:
                print "cannot create thumbnail for", infile
    else:
        print "not need create thumbnail for", infile

我还收集了一个python的小小手册,相当于是FAQ吧。

Share

让 viewvc 默认显示GB2312编码

默认的viewvc是显示UTF-8,不过可能有时候你的项目都是GB2312编码或者BIG5编码,需要改变其实很简单,在viewvc的安装目录下找到这个文件

1
$VIEWVC_INSTALL_DIR/lib/sapi.py

只需要把 UTF-8 替换成 GB2312 就可以了,一共有三个地方,使用 vim 来就是这样

1
:%s/=UTF-8/=GB2312/g

或者你可以改一下原代码,更为方便的改动和使用。

注意我使用的 viewvc 版本为dev-1.1,关于viewvc的安装请参考这篇日志,关于svn的安装请参考这篇日志

Share