时间:2021-07-01 10:21:17 帮助过:3人阅读
import urllib.request
import re
from mysql.connector import *
#爬取整个网页的方法
def open_url(url):
req=urllib.request.Request(url)
respond=urllib.request.urlopen(req)
html=respond.read().decode(‘utf-8‘)
return html
#爬取每个页面中每一话漫画对应的链接
def get_url_list(url):
html=open_url(url)
p=re.compile(r‘<a href="(.+)" title=".+ <br>.+?">‘)
url_list=re.findall(p,html)
return url_list
#自动进入每一话漫画对应的链接中爬取每一张图片对应的链接并插入到mysql数据库
def get_img(url):
#获取每个页面中每一话漫画对应的链接
url_list=get_url_list(url)
#连接mysql数据库
conn=connect(user=‘root‘,password=‘‘,database=‘test2‘)
#创建游标
c=conn.cursor()
try:
#创建一张数据库表
c.execute(‘create table cartoon(name varchar(30) ,img varchar(100))‘)
except:
#count用来计算每一张网页有多少行数据被插入
count=0
for each_url in url_list:
html=open_url(each_url)
p1=re.compile(r‘<img src="(.+)" alt=".+?>‘)
p2=re.compile(r‘<h1>(.+)</h1>‘)
img_list=re.findall(p1,html)
title=re.findall(p2,html)
for each_img in img_list:
c.execute(‘insert into cartoon values(%s,%s)‘,[title[0],each_img])
count+=c.rowcount
print(‘有%d行数据被插入‘%count)
finally:
#提交数据,这一步很重要哦!
conn.commit()
#以下两步把游标与数据库连接都关闭,这也是必须的!
c.close()
conn.close()
num=int(input(‘前几页:‘))
for i in range(num):
url=‘http://www.ishuhui.com/page/‘+str(i+1)
get_img(url)
这是数据库的结果:

代码已经注释的很清晰了。这里需要注意的是要去下载mysql-connector-python模块,这是一个python与mysql连接的模块,直接
pip install mysql-connector-python --allow-external mysql-connector-python
可以看出用python写爬虫并把数据存入数据库是很简单的,这也是python优雅的地方!当然,这只是一个很简单的爬虫系统,还有很多细节要去完善,只适合小
数据。但是学习都是从简单的开始嘛。
http://www.cnblogs.com/tester-zhenghan/p/4887838.html
用python3.x与mysql数据库构建简单的爬虫系统(转)
标签: