1、爬取页面 http://www.quanshu.net/book/9/9055/

2、用到模块urllib(网页下载),re正则匹配取得title及titleurl,urlparse(拼接完整url),MySQLdb(导入MySQL) 数据库

3、for 循环遍历列表 取得盗墓笔记章节title 和 titleurl

4、try except 异常处理

5、python 代码

#-*-coding: utf-8 -*-
import urllib
import re
import urlparse
import MySQLdb
rooturl='http://www.quanshu.net/book/9/9055/'
#getlist返回包含title 和titleurl的列表
def getlist(url):
html=urllib.urlopen(url).read()
html=html.decode('gb2312').encode('utf-8')
reg=r'<li><a href="(.*?)" title=".*?">(.*?)</a></li>'
return re.findall(reg,html)
try:
conn = MySQLdb.connect(host='localhost', user='root', passwd='Admin@', db='local_db', port=3306, charset='utf8')
with conn:
cursor = conn.cursor()
#如果存在daomubiji数据表先删除
drop_table_sql='DROP TABLE IF EXISTS daomubiji'
cursor.execute(drop_table_sql)
conn.commit()
#如果存在daomubiji数据表 先删除后接着创建daomubiji表
create_table_sql = '''
CREATE TABLE daomubiji (
ID INT(11),
title VARCHAR(255),
titleurl VARCHAR(255)
)ENGINE=INNODB DEFAULT CHARSET=utf8
'''
cursor.execute(create_table_sql)
conn.commit()
#下面调用getlist()函数获取rooturl下所有章节的titleurl 和title 组成的列表
urllist = getlist(rooturl)
#href属性取得的url不完整 仅取出了完整url的右半段 因此下面for循环变量名起名righturl
ID=0
#对列表进行遍历 取 titleurl 和title
for righturl in urllist:
title = righturl[1]
newurl = righturl[0]
#urlparse 模块的urlparse.urljoin方法将righturl 按照rooturl格式拼接成完整url
titleurl = urlparse.urljoin(rooturl, newurl)
ID+=1
print ID,title, titleurl
cursor.execute("INSERT INTO daomubiji values(%s,%s,%s)", (ID,title, titleurl))
conn.commit()
print "输入了"+ str(ID) +"条数据"
except MySQLdb.Error:
print "连接失败!"

  


代码执行情况:

6、MySQL数据库查询是否导入成功

SELECT * FROM daomubiji

  

 7、执行成功

最新文章

  1. codevs1048 石子合并
  2. Java多线程简析
  3. 第四章 使用Docker镜像和仓库(二)
  4. / etc / init.d / iptables: line 268: restorecon: command not found
  5. afddaf
  6. 【转】Hive学习路线图
  7. 【windows核心编程】IO完成端口(IOCP)复制文件小例前简单说明
  8. 【设计模式 - 21】之空对象模式(Null Object)
  9. Linux系统下搭建DNS服务器——DNS原理总结
  10. Kattis - Peragrams
  11. Problem : 1196 ( Lowest Bit )
  12. Codeforces Round #402 (Div. 1)
  13. 报错!!!Servlet.service() for servlet [action] in context with path [/myssh] threw exception [java.lang.NullPointerException] with root cause java.lang.NullPointerException
  14. android sdk 安装 配置
  15. 20175212童皓桢 Java实验二-面向对象程序设计实验报告
  16. springboot下整合各种配置文件
  17. Vue初学者可能不知道的坑
  18. Ubuntu14.04 + Text-Detection-with-FRCN(CPU)
  19. JSP 过滤器
  20. win32 MSG 值

热门文章

  1. Eos持久化实体
  2. C++学习笔记21:文件系统
  3. SpringMVC 用http请求的Get和Post请求作为路由的方法的重载方式
  4. 修改mysql用户名密码 和 PHPmysqlAdmin对应密码修改
  5. Java--&gt;Json解析网页数据
  6. 史上最详细Windows版本搭建安装React Native环境配置 转载,比官网的靠谱亲测可用
  7. web安全之http协议
  8. [20150522]RPM包的管理
  9. (转)CVPR 2016 Visual Tracking Paper Review
  10. Spring MVC小结