温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Python练习【爬取银行网站信息】

发布时间:2020-06-18 05:51:22 来源:网络 阅读:586 作者:流域哈哈 栏目:编程语言

功能实现

爬取所有银行的银行名称和官网地址(如果没有官网就忽略),并写入数据库; 银行链接: http://www.cbrc.gov.cn/chinese/jrjg/index.html

编程思路

1.利用url访问页面并获取页面信息 2.利用正则表达式对页面信息进行筛选,获取我们需要的信息 3.保存至Mysql数据库中

1.获取网页信息并保存至文件

from urllib.request import urlopen # 获取页面信息 def getPageInfo(url): pageInfo = urlopen(url) content = pageInfo.read().decode('utf-8') return content # 主函数 def main(): url = 'http://www.cbrc.gov.cn/chinese/jrjg/index.html' pageInfo = getPageInfo(url) print(pageInfo)

Python练习【爬取银行网站信息】

  • 一些网站常常通过判断 UA(User-Agent用户代理) 来给不同的操作系统、不同的浏览器发送不同的页面,因此可能造成某些页面无法在某个浏览器中正常显示,但通过伪装 UA 可以绕过检测。
    查看浏览器UA

    Python练习【爬取银行网站信息】

    获取页面信息
def main(): url = 'http://www.cbrc.gov.cn/chinese/jrjg/index.html' #修改UA,伪装成浏览器,以获取相应页面 user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko Core/1.63.6788.400 QQBrowser/10.3.2864.400" reqObj = request.Request(url, headers={'User-Agent': user_agent}) pageInfo = getPageInfo(reqObj) print(pageInfo)

保存到文件方便查看
# 保存到文件pageContent def saveInfo(data): with open('doc/pageContent','w+',encoding='utf-8') as f: f.write(data)

2.利用正则筛选所需信息

Python练习【爬取银行网站信息】

图中是获取的页面信息中所需信息中的一例 需要获取其中的 网址 和 银行名称 使用的正则表达式为'<a href="(http.*?)".*?>\s+(.+?)\s+?</a>' 这里注意利用\s+匹配额外的\t和\n
# 利用正则匹配获取信息 def getInfo(data): pattern = r'<a href="(http.*?)".*?>\s+(.+?)\s+?</a>' info = re.findall(pattern ,data) print(info)
匹配到的信息:

Python练习【爬取银行网站信息】


3.保存数据至数据库

首先在mysql中创建一个名为bankUrl的数据库

Python练习【爬取银行网站信息】

连接数据库
## 连接数据库 conn = pymysql.connect( host='localhost', # 主机名 user='root', # 用户名 password='mysql', # 密码 database='bankUrl', # 连接对应数据库 charset='utf8', # utf-8编码 autocommit=True # 自动提交数据 ) cur = conn.cursor() # 创建游标 # 删除重建表格来刷新每次写入的数据 cur.execute('drop table bankurl') creatTableSql = 'create table if not exists bankUrl(银行名称 varchar(20),网址 varchar(100))default charset=utf8;' cur.execute(creatTableSql) # 写入数据库 for item in getInfo(pageInfo): insertSql = 'insert into bankUrl(银行名称,网址) value("{1}","{0}")'.format(item[0],item[1]) cur.execute(insertSql)

完整代码:

import re import time from urllib import request from urllib.request import urlopen import pymysql def timeCounter(fun): def wrapper(*arg ,**kwargs): startTime = time.time() fun(*arg,**kwargs) endTime = time.time() print(fun.__name__+'运行时间为%.2f'%(startTime-endTime)) return wrapper # 获取页面信息 def getPageInfo(url): pageInfo = urlopen(url) content = pageInfo.read().decode('utf-8') return content # 保存页面信息到文件 def saveInfo(data): with open('doc/pageContent','w+',encoding='utf-8') as f: f.write(data) # 利用正则匹配获取信息 def getInfo(data): pattern = r'<a href="(http.*?)".*?>\s+(.+?)\s+?</a>' info = re.findall(pattern ,data) return info @timeCounter def main(): url = 'http://www.cbrc.gov.cn/chinese/jrjg/index.html' user_agent = "Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko Core/1.63.6788.400 QQBrowser/10.3.2864.400" reqObj = request.Request(url, headers={'User-Agent': user_agent}) pageInfo = getPageInfo(reqObj) # saveInfo(pageInfo) conn = pymysql.connect( host='localhost', user='root', password='mysql', database='bankUrl', charset='utf8', autocommit=True, # 如果插入数据,, 是否自动提交? 和conn.commit()功能一致。 ) cur = conn.cursor() # cur.execute('create database if not exists bankUrl;') cur.execute('drop table bankurl') creatTableSql = 'create table if not exists bankUrl(银行名称 varchar(20),网址 varchar(100))default charset=utf8;' cur.execute(creatTableSql) for item in getInfo(pageInfo): insertSql = 'insert into bankUrl(银行名称,网址) value("{1}","{0}")'.format(item[0],item[1]) cur.execute(insertSql) if __name__ == '__main__': main()

查询结果

Python练习【爬取银行网站信息】

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI