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

分析网页结构

目标网页: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 table2
colleage_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 pymysql


class 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 re
import urllib.request

from bs4 import BeautifulSoup

# 储存全国大学数据
from spider_for_csu.colleage.DBUtil import DBUtil

index_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 table2
colleage_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

  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值