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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
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文档

posted on   似不是傻  阅读(355)  评论(0编辑  收藏  举报

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示