青青草免费线看线看|啊在车上停不下来了|国产少女免费观看电视剧|仑乱88MAV|精品老司机在线观看视频|国产一区二区三区高清免费视频|在线观看免费777av

Python爬取數(shù)據(jù)保存到數(shù)據(jù)庫怎么做?Python爬蟲抓取數(shù)據(jù)如何保存到數(shù)據(jù)庫

【Python爬取數(shù)據(jù)保存到數(shù)據(jù)庫怎么做?Python爬蟲抓取數(shù)據(jù)如何保存到數(shù)據(jù)庫】python爬蟲程序抓取數(shù)據(jù)返回之后是需要保存到文件或者是數(shù)據(jù)庫之中的 , 而保存到數(shù)據(jù)庫里面的話就需要經(jīng)過一些其他處理了 。下文會以爬蟲抓取數(shù)據(jù)返回 , 并且保存到mysql數(shù)據(jù)庫為示例來詳細(xì)講解python爬取數(shù)據(jù)保存到數(shù)據(jù)庫是如何實(shí)現(xiàn)的 。

Python爬取數(shù)據(jù)保存到數(shù)據(jù)庫怎么做?Python爬蟲抓取數(shù)據(jù)如何保存到數(shù)據(jù)庫


一、定義類
因?yàn)閙ysql這種數(shù)據(jù)庫是關(guān)系型數(shù)據(jù)庫 , 它保存數(shù)據(jù)庫都是以字段來劃分的 。所以在定義好數(shù)據(jù)表結(jié)構(gòu)之后 , 在python中還得創(chuàng)建出來一個(gè)和列名數(shù)量相同的類出來才可以 , 代碼示例如下所示:
# 導(dǎo)入模塊import requestsfrom lxml import etreeimport pymysql# 定義類class articleData():    def __init__(self, title, abstract, path,date):        self.title = title        self.abstract = abstract         self.path = path        self.date = date在這個(gè)類中總共是有四個(gè)屬性 , 它也就對應(yīng)著數(shù)據(jù)表里面的四個(gè)字段 。
二、定義數(shù)據(jù)保存函數(shù)
那么第二步就是要定義一個(gè)數(shù)據(jù)保存函數(shù)了 , 該函數(shù)需要將類實(shí)例對象給傳遞進(jìn)來 。然后在函數(shù)中創(chuàng)建mysql數(shù)據(jù)庫庫連接對象以及游標(biāo) , 再調(diào)用execute()方法并且傳入insert這種添加數(shù)據(jù)的sql語句即可 。最后還需要提交修改請求并關(guān)閉連接 , 代碼如下所示:
def saveData(DataObject):  count = pymysql.connect(host='localhost',port=3306,user='root',password='123456',db='test' )  db = count.cursor()  sql = f"insert into article_detail(title,abstract,path,date) " \  f"values ('{DataObject.title}','{DataObject.abstract}','{DataObject.path}','{DataObject.date}')"  db.execute(sql)  count.commit()  db.close()三、定義數(shù)據(jù)爬取函數(shù)
那么數(shù)據(jù)保存函數(shù)以及用來映射數(shù)據(jù)庫結(jié)構(gòu)的類都創(chuàng)建好之后 , 最后要做的就是爬取數(shù)據(jù)并且將其處理成類實(shí)例對象了 。調(diào)用get()方法訪問網(wǎng)頁之后返回?cái)?shù)據(jù) , 然后用xpat庫解析數(shù)據(jù)后通過節(jié)點(diǎn)來得到數(shù)據(jù) , 最后實(shí)例化成類對象并且調(diào)用saveData()這個(gè)保存爬蟲數(shù)據(jù)到數(shù)據(jù)庫的方法即可 , 詳細(xì)代碼示例如下所示:
def getWebData():    url = "https://blog.csdn.netin?spm=10001.5343"    html = requests.get(url=url, headers=header)    etreeHtml = etree.HTML(html.text)    dataHtml = etreeHtml.xpath('//*[@class="mainContent"]/div/div/div')    for _ in dataHtml:        title = ''.join(_.xpath('./article/a/div[1]/h4/text()'))         abstract = ''.join(_.xpath('./article/a/div[2]/text()'))         path = ''.join(_.xpath('./article/a/@href'))         date = ''.join(_.xpath('./article/a/div[3]/div/div[2]/text()')).replace(' ','').replace('·','').replace('發(fā)布博客','')         article_data = articleData(title,abstract,path,date)        saveData(article_data)if __name__ == "__main__":  getWebData()

猜你喜歡