个人知乎 ##基础九——爬虫入门PySpider

来源:互联网 发布:ecshop sql注入漏洞 编辑:程序博客网 时间:2024/05/22 00:34

个人知乎

基础九——爬虫入门PySpider

爬虫基础框架

安装:pip install pyspiderscheduler:调度器,调度一个url处理fetcher:下载网页器processor:处理网页器,并解析出新的url
class Handler(BaseHandler):    crawl_config = {    }    @every(minutes=24 * 60)    def on_start(self):        self.crawl( 'http://scrapy.org/', callback=self.index_page)    @config(age=10 * 24 * 60 * 60)    def index_page(self, response):        for each  in response.doc( 'a[href^="http"]').items():        self.crawl(each.attr.href, callback=self.detail_page)    @config(priority=2)    def detail_page(self, response):        return {        "url": response.url,        "title": response.doc( 'title').text(),        }

Response/PyQuery

<参考资料: http://docs.pyspider.org/en/latest/apis/Response/>
< PyQuery:https://pythonhosted.org/pyquery/api.html >
< css选择器参考资料:http://www.w3school.com.cn/cssref/css_selectors.asp>

一个网页的框架    doc    url    text    header    cookiescss选择器:标签解析    自定义选中html标签    .class:class='class'    #id:id='id'    div.inner:<div class='inner'>    a[href^="http://"] :带http开头的a标签    p>div>span:p标签下的div下的span,一层的    p div:在内层即可,不要求父子    [target=_blank]:Target=_blank
#例子q=PyQuery(open('v2ex.html').read())print q('title').text()for each in q('div.inner>a').items():#获取属性    print 1,each.attr.href#获取文本    print 2,each.html()

Python和MySQL:MySQLdb

python的内嵌sql
#连接数据库db = MySQLdb.connect( 'localhost',  'root',  'nowcoder',  'wenda',charset= 'utf8')try:#游标处理多条结果    cursor = db.cursor()    #插入    sql =  'insert into question(title, content, user_id, created_date,    comment_count) values ("%s","%s",%d, %s, %d)' % (    'title',  'content', random.randint(1, 10),  'now()', 0);    # print sql    cursor.execute(sql)    #最后新条目的id    qid = cursor.lastrowid    #所有事务需要提交到数据库    db.commit()    print qid#异常处理except Exception, e:    print e    #事物回滚    db.rollback()#断开连接db.close()#查取db = MySQLdb.connect( 'localhost',  'root',  'nowcoder',  'wenda',charset= 'utf8')try:    cursor = db.cursor()    sql =  'select * from question order by id desc limit 2'    cursor.execute(sql)    #fetchall获取条目列表    for each  in cursor.fetchall():    #每个each都是一个属性列表        for row  in each:            print row    #db.commit()except Exception, e:    print e    db.rollback()db.close()

爬虫实践

#v2ex#知乎