• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

一个咸鱼的Python爬虫之路(4):将爬取数据存入mysql_mysql

mysql 搞代码 7年前 (2018-06-09) 208次浏览 已收录 0个评论

一个咸鱼的Python爬虫之路(四):将爬取数据存入mysql

Python 与 mysql 数据连接 用pymysql

import pymysql    conn =pymysql.connect(host='127.0.0.1',user='root',password='123456',db='company',charset="utf8")  cur=conn.cursor() sql=‘’‘

’‘’ employee=cur.execute(sql) conn.commit() cur.close() conn.close()

基本操作大概就这样
这次爬取的是淘宝商品页面

过程就略了放代码

import requests import re import pymysql   def getHTMLtext(url):     try:        r=requests.get(url,timeout=100)        r.raise_for_status()        r.encoding=r.apparent_encoding        return r.text     except:         return "" def getpage(itl,html):     try:         plt=re.findall(r'"view_price":"[/d.]*"',html)         nlt=re.findall(r'"raw_title":".*?"',html)         for i in range(len(plt)):             price = eval(plt[i].split(':')[1])             title = eval(nlt[i].split(':')[1])             itl.append([price, title])     except:        print("")   def printgoods(itl):     tplt = "{:2}/t{:8}/t{:16}"     print(tplt.format("序号", "价格", "商品名称"))      count = 0     conn = pymysql.connect(host='127.0.0.1', user='root', password='123456', db='company',charset="utf8")      cur = conn.cursor()      sqlc = '''                 create table coffee(                 id int(11) not null auto_increment primary key,                 name varchar(255) not null,                 price float not null)DEFAULT CHARSET=utf8;                 '''      try:         A = cur.execute(sqlc)         conn.commit()         print('成功')     except:         print("错误")     for g in itl:         count = count + 1         b=tplt.format(count, g[0], g[1])            sqla = '''         insert into  coffee(name,price)         values(%s,%s);        '''         try:             B = cur.execute(sqla,(g[1],g[0]))             conn.commit()             print('成功')         except:             print("错误")          # save_path = 'D:/taobao.txt'         # f=open(save_path,'a')         #         # f.write(b+'/n')         # f.close()      conn.commit()     cur.close()     conn.close()   def main():     goods="咖啡"     depth =2     start_url='https://s.taobao.com/search?q='+goods     List =[]     for i in range(depth):         try:             url =start_url +"&s="+ str(i*44)             html=getHTMLtext(url)             getpage(List,html)         except:            continue       print(printgoods(List))     # savefiles(data)     main()

一个咸鱼的Python爬虫之路(4):将爬取数据存入mysql_mysql

可以看到所需要的数据已经存入数据库了

欢迎大家阅读《一个咸鱼的Python爬虫之路(4):将爬取数据存入mysql_mysql》,跪求各位点评,by 搞代码


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:一个咸鱼的Python爬虫之路(4):将爬取数据存入mysql_mysql
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址