• 把爬取到的链接放到数据库


    把爬取到的链接放到数据库

    import requests  # 用来请求网页
    from bs4 import BeautifulSoup  # 解析网页
    import time  # 设置延时时间,防止爬取过于频繁被封IP号
    import re  # 正则表达式库
    import mysql  # 由于爬取的数据太多,我们要把他存入MySQL数据库中,这个库用于连接数据库
    import mysql.connector
    import logging
    
    con = mysql.connector.connect(
        user="root",
        password='123456',
        host='localhost',
        port='3306',
        database='test_url'
    )
    
    # insertSql = "INSERT INTO ww (`url`) VALUES (%s)"
    
    cursor = con.cursor()
    
    url = "https://book.douban.com/tag/?icn=index-nav"
    
    wb_data = requests.get(url)  # 请求网址
    soup = BeautifulSoup(wb_data.text, "lxml")  # 解析网页信息
    tags = soup.select("#content > div > div.article > div > div > table > tbody > tr > td > a")
    
    # 根据CSS路径查找标签信息,CSS路径获取方法,右键-检查-copy selector,tags返回的是一个列表
    
    #f = open("channel/channel.html", 'w')
    
    insertSql = "INSERT INTO wangzhi (dizhi) VALUES (%s)"
    
    for tag in tags:
    
        tag = tag.get_text()  # 将列表中的每一个标签信息提取出来
    
        helf = "https://book.douban.com/tag/"
        # 观察一下豆瓣的网址,基本都是这部分加上标签信息,所以我们要组装网址,用于爬取标签详情页
        urlVal = helf + str(tag)
        # f.write("%s<br>" % url)
    
        try:
    
            # cursor.execute("INSERT INTO wangzhi VALUES urlVal")
            cursor.execute("INSERT into `ww` (`dizhi`) values('%s')" % urlVal)
    
            con.commit()
    
        except Exception as err:
    
            print(err)
            
    
    con.close()
    cursor.close()
    

      把注释的代码打开,就是把爬去到的链接写到文件夹中,不用创建文件夹,自动生成文件夹和html文档

  • 相关阅读:
    DPDK ring简单说明
    DPDK初始化流程
    从《雪白血红》说起(2)
    从《雪白血红》说起(1)
    苏联印象(1)-过往与想象
    DPDK ip分片与重组的设计实现
    linux协议栈分析-序
    DPDK与QoS(服务质量)
    DPDK LPM路由存储与查找
    《教父》曾说
  • 原文地址:https://www.cnblogs.com/yongxinboy/p/7840959.html
Copyright © 2020-2023  润新知