持久化存儲-本地Excel文件及MySQL數(shù)據(jù)庫

當(dāng)前問題(已解決)

安裝好了pymysql之后,在Anaconda Powershell Prompt中運(yùn)行爬蟲文件抓取。無報錯提示
然而點開Mysql數(shù)據(jù)庫,亦未發(fā)現(xiàn)有數(shù)據(jù)儲存。目前原因未知。

具體情況

piplines.py中的代碼文件如下:

from itemadapter import ItemAdapter
import pandas as pd
import pymysql


class Project1Pipeline:
    def process_item(self, item, spider):
        title=item['title']
        date=pd.DataFrame({'文章標(biāo)題':title})
        date.to_excel('D:\文章題目.xlsx',index=False)
        return item

class store_to_Mysql:
   def process_item(self, item, spider):
       connect_item=pymysql.connect(host='localhost',user='root',password='wynews')
       youbiao=connect_item.cursor()
       data=[(a) for a in zip(item['title'])]
       print(data)
       try:
           sql="insert into wy(a) values (%s)"
           youbiao.executemany(sql,data)
           connect_item.commit()
       except:
           connect_item.rollback()
       return item
       youbiao.close()
       connect_item.close()
問題解決說明

原因已查明,如涉及到是MySQL數(shù)據(jù)庫的問題,比如在數(shù)據(jù)庫中創(chuàng)建的表名和Scrapy框架中的代碼名不匹配。則在命令行窗口運(yùn)行時,很多時候也不會有報錯提示。

正確的piplines.py中的代碼文件如下;

from itemadapter import ItemAdapter
import pandas as pd
import pymysql


class Project1Pipeline:
    def process_item(self, item, spider):
        title=item['title']
        date=pd.DataFrame({'文章標(biāo)題':title})
        date.to_excel('D:\文章題目.xlsx',index=False)
        return item

class store_to_Mysql:
   def process_item(self, item, spider):
       connect_item=pymysql.connect(host='localhost',user='root',password='dd521!',database='wynews',charset='utf8')
       youbiao=connect_item.cursor()
       data=[(a) for a in zip(item['title'])]
       print(data)
       try:
           sql="insert into wynews(文章標(biāo)題) values (%s)"
           youbiao.executemany(sql,data)
           connect_item.commit()
       except:
           connect_item.rollback()
       return item
       youbiao.close()
       connect_item.close()

對應(yīng)的MySQL數(shù)據(jù)庫中表的結(jié)構(gòu)如圖所示:


image.png

備注:1)重點的代碼為下述兩句話:
connect_item=pymysql.connect(host='localhost',user='root',password='dd521!',database='wynews',charset='utf8')
2)這個是輸入管理員秘密,及對應(yīng)的數(shù)據(jù)庫的名稱-wynews
try:
sql="insert into wynews(文章標(biāo)題) values (%s)"
youbiao.executemany(sql,data)
connect_item.commit()
這個是將已獲得的數(shù)據(jù)插入wynews(文章標(biāo)題) ——名為wynews的表,其中的“文章標(biāo)題”這一列之下。
所以,都是一一對應(yīng)且指定的。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容