美文网首页Py
爬虫爬取哔哩哔哩视频相关数据存入MySQL

爬虫爬取哔哩哔哩视频相关数据存入MySQL

作者: 真夜猫 | 来源:发表于2019-01-09 17:59 被阅读150次

    今天给大家带来的是哔哩哔哩数据爬取并存入MySQL数据库的爬虫,话不多说,小编来带领大家一步步完成。

    需导入的库

    import requests
    from lxml import etree
    import time
    from fake_useragent import UserAgent
    import pymysql
    

    爬取网页主体函数

    真夜猫.JPG

    这是一个html网页,所以我们下面直接使用xpath将所需的数据提取出来就行了

    代码:

    ua = UserAgent(use_cache_server=False)
    infos=[]
    def spider(url):
        try:
            response=requests.get(url,headers={"User-Agent":ua.random})
        except:
            try:
                if response.status_code !=200:
                    response = requests.get(url, headers={"User-Agent": ua.random})
            except:
                pass
    
        try:
            HTML=etree.HTML(response.text)
            lis=HTML.xpath('//ul[@class="video-contain clearfix"]/li')
            for li in lis:
                info={
                        'title':li.xpath('./a/@title')[0],
                        'href':"https:"+li.xpath('./a/@href')[0],
                        'time':li.xpath('.//span/text()')[0].strip()
                }
                infos.append(info)
        except:
            pass
    

    存储入mysql:

    我们这里想将数据存入数据库,首先需要先连接数据库,将相关参数填对。再创建游标,写mysql执行语句来实现我们想要的操作。

    代码:

    def save_to_mysql(key,infos):
        conn = pymysql.connect(host='localhost', user='root', password='0000',
                               database='pymysql_demo', port=3306)
        cursor = conn.cursor()
        sql_createTb = """CREATE TABLE IF NOT EXISTS  {}(
                         id INT NOT NULL AUTO_INCREMENT,
                         title  VARCHAR(500),
                         href char(80),
                         time CHAR(80),
                         PRIMARY KEY(id))
                         """.format(key)
        cursor.execute(sql_createTb)
        for info in infos:
            title=info['title']
            href=info['href']
            time=info['time']
            sql = '''
            insert into {}(title,href,time) value(%s,%s,%s)
            '''.format(key)
            cursor.execute(sql, (title,href,time))
            conn.commit()
        conn.close()
    

    控制主函数

    我们使用主函数来实现参数的传递,并依次控制网页爬取函数与数据保存函数。

    代码:

    def main():
        key=input("请输入搜索内容:")
        pages=int(input("爬取页数:"))
        for page in range(1,pages+1):
            print("第"+str(page)+"页")
            url="https://search.bilibili.com/all?keyword="+str(key)+"&page="+str(page)+""
            spider(url)
        print(infos)
        save_to_mysql(key,infos)
    
    if __name__ == '__main__':
        main()
    

    运行效果如下:

    python:
    真夜猫.JPG
    MySQL:
    真夜猫.JPG

    这里我们已经顺利了完成了我们的要求,将数据成功存入了mysql,还等什么,赶快去试试吧!

    相关文章

      网友评论

        本文标题:爬虫爬取哔哩哔哩视频相关数据存入MySQL

        本文链接:https://www.haomeiwen.com/subject/xtigrqtx.html