python2.7 爬虫_爬取小说盗墓笔记章节及URL并导入MySQL数据库_20161201
2024-08-20 22:06:52
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、执行成功
最新文章
- codevs1048 石子合并
- Java多线程简析
- 第四章 使用Docker镜像和仓库(二)
- / etc / init.d / iptables: line 268: restorecon: command not found
- afddaf
- 【转】Hive学习路线图
- 【windows核心编程】IO完成端口(IOCP)复制文件小例前简单说明
- 【设计模式 - 21】之空对象模式(Null Object)
- Linux系统下搭建DNS服务器——DNS原理总结
- Kattis - Peragrams
- Problem : 1196 ( Lowest Bit )
- Codeforces Round #402 (Div. 1)
- 报错!!!Servlet.service() for servlet [action] in context with path [/myssh] threw exception [java.lang.NullPointerException] with root cause java.lang.NullPointerException
- android sdk 安装 配置
- 20175212童皓桢 Java实验二-面向对象程序设计实验报告
- springboot下整合各种配置文件
- Vue初学者可能不知道的坑
- Ubuntu14.04 + Text-Detection-with-FRCN(CPU)
- JSP 过滤器
- win32 MSG 值