本文主要是介绍个人知乎 ##基础九——爬虫入门PySpider,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
个人知乎
基础九——爬虫入门PySpider
爬虫基础框架
安装:pip install pyspider
scheduler:调度器,调度一个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>
一个网页的框架docurltextheadercookies
css选择器:标签解析自定义选中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 sqlcursor.execute(sql)#最后新条目的idqid = 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 edb.rollback()
db.close()
爬虫实践
#v2ex
#知乎
这篇关于个人知乎 ##基础九——爬虫入门PySpider的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!