python语言写一个简单的京东爬取,数据存入数据库

程序要求

(1)使用渲染库、解析库、pymysql库。
(2)数据量>3W条(视实际情况)。
(3)利用Python编写函数,用户可以通过输入简单的参数来查询数据(查询方式分为模糊查询和精确查询),如爬取的是男装数据的十个品牌,可以输入夹克,进而模糊匹配查询所有符合的夹克信息(精确和模糊查询至少一种对应一个查询)。

开发环境及工具

PyCharm Community Edition
在这里插入图片描述
MySQL 8.0 Command Line Client
在这里插入图片描述
谷歌浏览器
在这里插入图片描述

代码实现

程序代码
import requests
from pyquery import PyQuery as pq
import pymysql
import time
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from bs4 import BeautifulSoup

def shousuo(s):
    # 找到搜索栏,并且输入需要搜索的商品
    driver.find_element_by_class_name('text').send_keys(s)
    # 模拟键盘回车事件
    driver.find_element_by_class_name('button').send_keys(Keys.ENTER)
def chanpin(s):
    # 获取全局变量
    global flag
    global sign
    # 模拟下滑到页面底部
    for i in range(1, 5):
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight)")
        time.sleep(1)
    # 接受获取到的内容
    soup = BeautifulSoup(driver.page_source, 'lxml')
    li = soup.select('.gl-item')
    # 对内容进行筛选
    for goods in li :
        title1 = goods.select('.gl-i-wrap .p-name.p-name-type-2 a')[0].text
        #标题
        price1 = goods.select('.gl-i-wrap .p-price i')[0].text
        #价格
        # 将筛选之后的信息进行保存
        con = pymysql.connect(host='localhost', user='root', password='ltx3344cwx', port=3306, db='jd',charset='utf8')
        cursor = con.cursor()
        if(s == 1):
            sql = 'insert into yifu(title,price) values(%s,%s)'
        elif(s == 2):
            sql = 'insert into xiezi(title,price) values(%s,%s)'
        elif (s == 3):
            sql = 'insert into niuzaiku(title,price) values(%s,%s)'
        cursor.execute(sql, (title1, price1))
        con.commit()
        print(title1, price1)#在控制台输出爬取下来的数据,用于检测
    # 添加的判断退出条件,爬取N个页面
    flag = flag + 1
    if flag == ccc:
        sign = False
# 判断退出的全局变量
flag = 0
sign = True
#单查询
def chaxun1(s):
    b = input('你要查询的商品名称或价格:')
    print('你选择要查询的商品名称或价格是:' + b)
    con = pymysql.connect(host='localhost', user='root', password='ltx3344cwx', port=3306, db='jd',
                          charset='utf8')
    cursor = con.cursor()
    if (s == 1):
        sql1 = """select * from yifu where title like %s"""  # 标题模糊查询
        sql2 = """select * from xiezi where title like %s"""
        sql3 = """select * from niuzaiku where title like %s"""
    elif (s == 2):
        sql1 = """select * from yifu where title=%s"""  # 标题精确查询
        sql2 = """select * from xiezi where title=%s"""
        sql3 = """select * from niuzaiku where title=%s"""
    elif (s == 3):
        sql1 = """select * from yifu where price like %s"""  # 标题模糊查询
        sql2 = """select * from xiezi where price like %s"""
        sql3 = """select * from niuzaiku where price like %s"""
    elif (s == 4):
        sql1 = """select * from yifu where price=%s"""  # 价格精确查询
        sql2 = """select * from xiezi where price=%s"""
        sql3 = """select * from niuzaiku where price=%s"""
    cursor.execute(sql1,b)
    rs=cursor.fetchall()
    for r in rs:
        print(r)
    cursor.execute(sql2,b)
    rs=cursor.fetchall()
    for r in rs:
        print(r)
    cursor.execute(sql3,b)
    #con.commit()
    rs=cursor.fetchall()
    for r in rs:
        print(r)
#原始语句查询
def chaxun2():
    con = pymysql.connect(host='localhost', user='root', password='ltx3344cwx', port=3306, db='jd',
                          charset='utf8')
    cursor = con.cursor()
    try:
        cursor.execute(a)
        print('Count:', cursor.rowcount)
        row = cursor.fetchone()
        while row:
            print('查询结果:', row)
            row = cursor.fetchone()
    except:
        print('没有符合条件的数据')
# 使用selenium模块,模拟浏览器访问网页
aaa = input('请输入要查询的商品:')
bbb = int(input('请输入1,2,3选择要存入的数据库(建议上衣选择1,鞋子选择2,裤子选择3):'))
ccc = int(input('请输入浏览商品的页数:'))
print('您要查询的商品是:'+aaa)
print('您选择了数据库:'+str(bbb))
print('您打算查看商品的页数是:'+str(ccc))
url = 'https://www.jd.com/'
driver = webdriver.Chrome()
driver.implicitly_wait(3)
driver.get(url)
# 往shousuo()函数中传参数'
shousuo(aaa)
while sign:
    chanpin(bbb)
    # 模拟持续点击下一页
    next_btn = driver.find_element_by_class_name('pn-next')
    next_btn.click()
driver.close()

#select * from xiezi where title like '%休闲%'
ggg=int(input('请选择查询的方式:(单查询建议选1,原始语句建议选2)'))
if(ggg == 1):
    print('您选择了单查询')
    ddd = int(input('请输入1,2,3,4选择要查询的东西(商品名称模糊查询选择1,商品名称精准查询选择2,价格模糊查询选择3,价格精准查询选择4):'))
    print('您选择的查询方式是::' + str(ddd))
    chaxun1(ddd)
elif(ggg == 2):
    print('您选择了原始语句查询')
    a = input('请输入语句(yifu,xiezi,niuzaiku)')
    print('你的语句是' + a)
    chaxun2()

程序功能

1、可以在控制台输入要搜索的京东商品名称
2、自己选择要存入的数据库(取决于自己所建立的数据库数量)
3、自定义要浏览爬取的页数(不建议爬取太多,否则京东会弹出扫码验证,一般情况爬取50页左右,也就是3000条数据左右的时候会弹,想爬取大量数据,建议分多次爬取)
4、爬取下来的数据自动存入数据库
5、在控制台选择查询方式查找数据库中与之匹配的内容输出(实现了模糊查询和精准查询)

截图

数据库表截图

在这里插入图片描述

控制台运行截图

在这里插入图片描述在这里插入图片描述
初学python若有不当之处请多多指教

  • 2
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值