Python3.6爬虫练习之爬取全国大学省份数据

来源:互联网 发布:达内java速成班 编辑:程序博客网 时间:2024/06/02 16:39

分析网页结构

目标网页:http://www.huaue.com/gxmd.htm
这里写图片描述
经过F12分析网页结构分析,如图:
这里写图片描述
吐槽一下这里,这个网页的前端写的有毒,竟然会有两个相同的id…导致我在写爬虫程序的时候想了好久为什么一直爬取不到数据…如下图
这里写图片描述

编写小爬虫程序

Python3.6版本中可以直接使用urllib库来抓取GET请求到的网页数据,这里为了方便重用,使用了一个函数:

def load_page_content(link):    url_request = urllib.request.Request(link)    url_response = urllib.request.urlopen(url_request)    return url_response.read()

为了方便对网页数据进行分析,我们可以使用BeautifulSoup库。而Python3.6中的pip安装BeautifulSoup库会遇到语法错误,控制台显示如下:
这里写图片描述
显然是python版本问题…错误代码是python2版本的。
鉴于这种情况,我们可以这样安装:

pip install bs4

在python程序这样引用:

from bs4 import BeautifulSoup

使用方法也很简单,调用BeautifulSoup方法解析网页数据成树形结构,接下来就是遍历,具体操作可以参见文档说明

soup = BeautifulSoup(load_page_content(index_url), 'html.parser')table2 = soup.find_all('table', id='table2')  # id table2colleage_links = table2[1].find_all('a', attrs={'href': re.compile('http://www.huaue.com/gx*')})  # 正则匹配

数据库操作

使用pip安装pymysql模块

pip install pymysql

为了更好的复用这些代码,我们可以学习Java中JDBC的使用方法制作一个Util类

# mysql驱动连接import pymysqlclass DBUtil(object):    def __init__(self, db):        self.host = '127.0.0.1'        self.port = 3306        self.user = 'root'        self.password = 'root'        self.db = db    def connect(self):        try:            self.connect = pymysql.connect(host=self.host, port=self.port, user=self.user, passwd=self.password,                                           db=self.db, charset='utf8')            print('获取connect')            self.cursor = self.connect.cursor()  # 获取游标        except:            print('error in connect to mysql')    def save_to_index(self, content, url):        sql = "INSERT INTO `index`(name,url) VALUES('%s', '%s')" % (content, url)        print(sql)        try:            self.cursor.execute(sql)            print('插入当前数据%s成功' % content)            self.connect.commit()        except Exception:            print("insert failed." + Exception)

注意:

  1. 上面的插入操作一定要将connect对象提交,否则数据库无法正常保存数据
  2. 为了正常的使用sql语句操作字符串参数,这里使用了%s做替代符。其实也有另外一种方法,和JDBC一样使用?作为占位符,使用commit方法的时候按照参数顺序给?赋值

程序运行结果:
这里写图片描述

爬虫源码:

import reimport urllib.requestfrom bs4 import BeautifulSoup# 储存全国大学数据from spider_for_csu.colleage.DBUtil import DBUtilindex_url = 'http://www.huaue.com/gxmd.htm'  # 源网页def load_page_content(link):    url_request = urllib.request.Request(link)    url_response = urllib.request.urlopen(url_request)    return url_response.read()soup = BeautifulSoup(load_page_content(index_url), 'html.parser')table2 = soup.find_all('table', id='table2')  # id table2colleage_links = table2[1].find_all('a', attrs={'href': re.compile('http://www.huaue.com/gx*')})util = DBUtil('colleage')util.connect()  # 获取连接for temp_link in colleage_links:    util.save_to_index(temp_link.get_text(), temp_link['href'])

OS:其实,我真的很在乎 QK

阅读全文
1 0
原创粉丝点击