• python爬取数据库信息


    一、今日学习内容

      

    本文实例讲述了Python3爬虫学习之MySQL数据库存储爬取的信息。分享给大家供大家参考,具体如下:

    数据库存储爬取的信息(MySQL)

    爬取到的数据为了更好地进行分析利用,而之前将爬取得数据存放在txt文件中后期处理起来会比较麻烦,很不方便,如果数据量比较大的情况下,查找更加麻烦,所以我们通常会把爬取的数据存储到数据库中便于后期分析利用。

    这里,数据库选择MySQL,采用pymysql 这个第三方库来处理python和mysql数据库的存取,python连接mysql数据库的配置信息

    db_config ={

    'host': '127.0.0.1',

    'port': 3306,

    'user': 'root',

    'password': '',

    'db': 'pytest',

    'charset': 'utf8'

    }

    以爬取简书首页文章标题以及url为例,先分析抓取目标信息,

    如上图,文章题目在a标签中,且url(href)只含有后半部分,所以在存储的时候,最好把它补全。

    mysql:新建一个数据库pytest,建立一张名为titles的表,表中字段分别为id(int自增),title(varchar),url(varchar),如下:

    进行数据库操作的思路为:获得数据库连接(connection)->获得游标(cursor)->执行sql语句(execute)->事物提交(commit)->关闭数据据库连接(close),具体代码实现如下:

    # -*- coding:utf-8 -*-

    from urllib import request

    from bs4 import BeautifulSoup

    import pymysql

    # mysql连接信息(字典形式)

    db_config ={

    'host': '127.0.0.1',

    'port': 3306,

    'user': 'root',

    'password': '',

    'db': 'pytest',

    'charset': 'utf8'

    }

    # 获得数据库连接

    connection = pymysql.connect(**db_config)

    # 数据库配置,获得连接(参数方式)

    # connection = pymysql.connect(host='127.0.0.1',

    # port=3306,

    # user='root',

    # password='',

    # db='pytest',

    # charset='utf8')

    url = r'http://www.jianshu.com/'

    # 模拟浏览器头

    headers = {

    'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 Safari/537.36'

    }

    page = request.Request(url, headers=headers)

    page_info = request.urlopen(page).read().decode('utf-8')

    soup = BeautifulSoup(page_info, 'html.parser')

    urls = soup.find_all('a', 'title')

    try:

    # 获得数据库游标

    with connection.cursor() as cursor:

    sql = 'insert into titles(title, url) values(%s, %s)'

    for u in urls:

    # 执行sql语句

    cursor.execute(sql, (u.string, r'http://www.jianshu.com'+u.attrs['href']))

    # 事务提交

    connection.commit()

    finally:

    # 关闭数据库连接

    connection.close()

    代码执行结果:

    更多关于Python相关内容可查看本站专题:《Python Socket编程技巧总结》、《Python正则表达式用法总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

    希望本文所述对大家Python程序设计有所帮助。

    本文标题: Python3爬虫学习之MySQL数据库存储爬取的信息详解

    本文地址: http://www.cppcns.com/shujuku/mysql/247206.html

  • 相关阅读:
    20120109_1
    .NET(C#)开源代码分析
    Vue filter API All In One
    js 千位分隔符 All In One
    css fontfeaturesettings All In One
    vue 子组件不使用 watch 如何更新组件 All In One
    miro whiteboard All In One
    转载:sql注入的危害(登陆并获取数据库的名字,表的名称和字段)
    Windows 7/windows server 2008 R2 64位版IIS不能连接Access数据库,80004005报错的解决办法
    LINQ如何做SELECT TOP操作
  • 原文地址:https://www.cnblogs.com/feng747/p/14909836.html
Copyright © 2020-2023  润新知