Web Crawler With Python
Table of Contents

http://hi.baidu.com/cwyalpha/item/4d762ebbf3368cd285dd7953

Python 爬虫抓站 记录(虾米,百度,豆瓣,新浪微博)
python 下用到的库,urllib, urllib2, BeautifulSoup, cookielib, mechanize, re
看Firebug模拟浏览器行为。
1. 虾米
虾米不用登陆,没有IP限制,最简单。Python抓了下Xiami电台的试听数 里用的是
import urllib2
content = urllib2.urlopen('http://www.xiami.com/artist/top/id/1234').read()
每个歌手爬个两三页。把试听数10000以上的歌记下来。歌手id大概有11w。
处理网页用split, 正则表达式re.compile, BeautifulSoup都成。
( Beautiful Soup的中文文档 http://www.crummy.com/software/BeautifulSoup/bs3/documentation.zh.html )
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(content)
就能对soup操作了,支持正则表达式,譬如
soup.find('p', align=re.compile('^b.*'))['id']可以从 <p id="secondpara" align="blah"> 中抓出 secondpara, 可以通过这个抓到a href=""中间的url
soup.find("b", { "class" : "lime" })可以抓到 <b class="lime">Lime</b>
soup.find("b", { "class" : "lime" }).string 可以提取到<>与</>中间的内容 Lime。
2. 百度
如果想在空间里取米粒之类的操作就要登陆,mechanize比较好用。
import mechanize
import cookielib

  1. Browser

br = mechanize.Browser()

  1. Cookie Jar

cj = cookielib.LWPCookieJar()
br.set_cookiejar(cj)

  1. Browser options

br.set_handle_equiv(True)
br.set_handle_gzip(True)
br.set_handle_redirect(True)
br.set_handle_referer(True)
br.set_handle_robots(False)

br.addheaders = [('User-agent', 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.1) Gecko/2008071615 Fedora/3.0.1-1.fc9 Firefox/3.0.1')]
r = br.open('https://passport.baidu.com/?login&tpl=mn')
br.select_form(nr=0)
br.form['username']='abcabcabc' #用户名
br.form.find_control("password").readonly = False
br.form['password']='123123123' #密码
br.submit()
然后可以试试开个百度窗口看看自己的用户名在不在网页里
content = br.open('http://www.baidu.com').read()
print 'cwyalpha' in content
3. 新浪微博
新浪微博的登陆很麻烦。网上有很多模拟SinaSSO登陆的做法,比如
http://chen.yi.bo.blog.163.com/blog/static/15062110920120151191189/
http://denger.iteye.com/blog/1039052
http://community.itbbs.cn/thread/19120/
http://blog.csdn.net/xiaojianpitt/article/details/6440561
问题是SinaSSO的版本变化太快,半年前的登陆代码现在就不管用了。
之前主要爬新浪微群的用户,基本没有IP和访问数限制,可以直接把firefox的cookie抓过来用。用sqlite2cookie
def sqlite2cookie(filename):
from cStringIO import StringIO
from pysqlite2 import dbapi2 as sqlite
con = sqlite.connect(filename)
cur = con.cursor()
cur.execute("select host, path, isSecure, expiry, name, value from moz_cookies")
ftstr = ["FALSE","TRUE"]
s = StringIO()
s.write("""# Netscape HTTP Cookie File

  1. http://www.netscape.com/newsref/std/cookie_spec.html
  2. This is a generated file! Do not edit.

""")
for item in cur.fetchall():
s.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (
item[0], ftstr[item[0].startswith('.')], item[1],
ftstr[item[2]], item[3], item[4], item[5]))
s.seek(0)
cookie_jar = cookielib.MozillaCookieJar()
cookie_jar._really_load(s, '', True, True)
return cookie_jar

之后
cookiejar = sqlite2cookie(r'C:\Documents and Settings\a\Application Data\Mozilla\Firefox\Profiles\8mi38ldc.default\cookies.sqlite') #ff profile下的cookie地址
br = mechanize.Browser()

  1. Browser options

br.set_cookiejar(cookiejar)
爬微群的用户用到ajax,是POST方法。
r = br.open('http://q.weibo.com/ajax/members/page',
urllib.urlencode({'page':str(page),'gid':gid}),
timeout=30).read()
搜索是这样
searchq = '韩寒' #文件开头用utf8(# -*- coding:utf-8 -*-)
r = br.open('http://s.weibo.com/weibo/' + urllib.quote(searchq)).read()
新浪搜索限制是10s一个请求,单IP可以10个用户同时搜,最多返回50页,但可以把时间限制在某天某个小时内,所以基本够用。
4. 豆瓣
抓豆瓣短评不用登陆,但是手机版豆瓣单IP访问太多会封禁。网页版豆瓣单cookie单IP抓一小时就会让输验证码,可以用三个cookie轮流抓(三个都不用登陆)
上面的sqlite2cookie()函数是把整个cookie发出去,也可以把特定域名的cookie发出去
def sqlite2cookiehost(filename,host):
con = sqlite.connect(filename)
con.text_factory = str
cur = con.cursor()
cur.execute("select host, path, isSecure, expiry, name, value from moz_cookies where host like ?"
,['%%%s%%' % host])
ftstr = ["FALSE","TRUE"]
s = StringIO()
s.write("""# Netscape HTTP Cookie File

  1. http://www.netscape.com/newsref/std/cookie_spec.html
  2. This is a generated file! Do not edit.

""")
for item in cur.fetchall():
s.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (
item[0], ftstr[item[0].startswith('.')], item[1],
ftstr[item[2]], item[3], item[4], item[5]))
s.seek(0)
cookie_jar = cookielib.MozillaCookieJar()
cookie_jar._really_load(s, '', True, True)
return cookie_jar
调用
cookiejar = sqlite2cookiehost(r'C:\Documents and Settings\a\Application Data\Mozilla\Firefox\Profiles\8mi38ldc.default\cookies.sqlite', 'douban')
Chrome的cookie调用
def sqlite2cookieChrome(filename):#filename
#from pysqlite2 import dbapi2 as sqlite

## but we can make sqlite3 always return bytestrings …
# Cookies file come from C:\Users\JiangHonglei\AppData\Local\Google\Chrome\User Data\Default\Cookies
con = sqlite3.connect(filename)
con.text_factory = str

cur = con.cursor()
#cur.execute("select host, path, isSecure, expiry, name, value from moz_cookies")
cur.execute("select host_key, path, secure, expires_utc, name, value from cookies")

ftstr = ["FALSE","TRUE"]

s = StringIO()
s.write("""# Netscape HTTP Cookie File

  1. http://www.netscape.com/newsref/std/cookie_spec.html
  2. This is a generated file! Do not edit.

""")
for item in cur.fetchall():
try:
s.write("%s\t%s\t%s\t%s\t%s\t%s\t%s\n" % (
item[0], ftstr[item[0].startswith('.')], item[1],
ftstr[item[2]], item[3], item[4], item[5]))
except UnicodeError:
continue
s.seek(0)

cookie_jar = cookielib.MozillaCookieJar()
cookie_jar._really_load(s, '', True, True)
return cookie_jar
之后
cookiejarChrome = sqlite2cookieChrome(r'C:\Documents and Settings\a\Local Settings\Application Data\Google\Chrome\User Data\Default\Cookies')
IE的cookie比较特殊,每个域名的cookie分开存放,直接读取不能,从Temporary Internet Files里找到cookie拷出来用。。

cookiejarIE = mechanize.MSIECookieJar(delayload=True)
cookiejarIE.load_cookie_data(r'F:\BJ1KF314.txt')
5. 备注
爬豆瓣短评时碰到一些问题,比如碰到这种评论就会有utf8编码无法读取的错误

读内容的时候加ignore或者replace的参数,更多解释可以看u2b上watch?v=sgHbC6udIqc 这个视频
response = br.open(nextpageurl, timeout = 20)
content = response.read()
content = content.decode('utf-8','ignore')
最好在抓网页的时候加 except (urllib2.URLError, IOError): 排错,某些无法抓取的情况可能是网站把IP封了,另一种情况是这个页面真的是不存在。。。比如 见过大爷 这片子是没有评论没有打分的。。
mechanize和BeautifulSoup在处理之后最好手工清理下,否则内存占用会越来越大,
当网页不需要使用时要把mechanize的历史记录清了,br.clear_history()
BeautifulSoup存的内容用完最好也清掉,soup.decompose()
不清除历史记录很有可能爬1000个网页内存就要耗掉1G。。