當(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)且指定的。