爬取多個頁面的資料

Como0413發表於2018-01-18
程式碼如下:
# -*- coding:utf8 -*-
#匯入requests庫,取別名res
import requests as res
#匯入bs4包,取別名bs
from bs4 import BeautifulSoup as bs
#匯入資料庫驅動包
import MySQLdb
#宣告頁面從哪開始
j = 1
#迴圈遍歷每個頁面
while j <= 111:
    ##獲取目標網站的網頁
    #r代表將“”內的所有內容都預設為字串
    path = r"http://www.bengyechina.com/product/enterprise_alllist_0_0_0_" + str(j) + ".html"
    #請求獲取目標網頁的html
    doc = res.get(path)
    #準備要爬取資料的列表
    names = []
    imgs = []
    #需要bs解析器去解析網頁
    text = bs(doc.text,"html.parser")
    #從網頁中查詢類標籤名為plist的下標為0的所有內容
    p1 = text.select(".plist")[0]
    #從類標籤名為plist的下標為0的html中查詢標籤為li的內容中的img中所有內容
    img = text.select("li img")
    #宣告變數作為下標,並初始化
    i = 0
    #---------------爬取資料結束---------------
    #---------------資料寫入資料庫----------------
    #連線mysql資料庫中的pachong資料庫
    #connect("主機名","使用者名稱","密碼","資料庫名",charset = "utf8")
    conn = MySQLdb.connect("localhost","使用者名稱","密碼","pachong",charset = "utf8")
    #獲取遊標運算元據庫
    cursor = conn.cursor()
    #準備sql語句
    sql = "insert into bengye(name,img) "
    #迴圈往資料庫中新增資料
    for p2 in p1.select("li"):
        #p2代表每一個li標籤
        #獲取p2裡面的h2
        p3 = p2.select("h2")[0].select("a")[0].text
        #往列表中新增資料
        names.append(p3)
        imgs.append(img[i]["src"])
        # print names[i]
        # print "-----------------------"
        # print imgs[i]
        #判斷是否為新增資料的最後一條
        if i != len(p1.select("li")) - 1 :
            #mysql中的同時往表中插入多條資料的程式碼
            sql += " select '" +names[i]+"','"+imgs[i]+"' union \n"
        else :
            #mysql中的同時往表中插入多條資料的程式碼的最後一條程式碼
            sql += " select '" +names[i]+"','"+imgs[i]+"'"
        #累加器
        i = i + 1
    #執行sql語句
    cursor.execute(sql)
    #提交事物
    conn.commit()
    #關閉連結
    conn.close()
    #頁面的累加器
    j = j + 1
    # print "*****************"
    # print j
    # print "&&&&&&&&&&&&&&&&&&&&&&"

相關文章