生信-爬蟲 | 異步爬取網(wǎng)頁表格數(shù)據(jù)

寫在前面

前段時(shí)間,師姐讓爬取一些LncRNA的一些信息,具體在下面的網(wǎng)站中:
LncBook:https://ngdc.cncb.ac.cn/lncbook/lncrnas
由于這個(gè)表格是利用AJAX技術(shù)構(gòu)建的,因此利用傳統(tǒng)爬蟲獲取不到網(wǎng)頁的列表信息,且翻頁后URL不變,所以異步爬取順理成章的被利用起來了。我們可以按F12獲取一些蛛絲馬跡,從而幫助我們直接獲取表格信息。

技術(shù)實(shí)現(xiàn)

  • 以獲取LncBook表格信息為例

1、查看AJAX的構(gòu)成規(guī)律

  • 打開網(wǎng)頁,按【F12】,在【網(wǎng)絡(luò)】模塊下選擇【XHR】,刷新網(wǎng)頁。


    第一步

    第二步
  • 點(diǎn)擊Incall查看詳細(xì)信息,其中對(duì)我們有用的就是【請(qǐng)求URL】與【表單數(shù)據(jù)】


    詳細(xì)信息
  • 此時(shí)我們翻頁,查看二者的變化


    探索規(guī)律

結(jié)論

  • 我們采用【URL?page=】的結(jié)構(gòu)就可以訪問表格數(shù)據(jù)了(注意【?】不可省略),舉例:
https://ngdc.cncb.ac.cn/lncbook/lncrnas/lncall?page=1
https://ngdc.cncb.ac.cn/lncbook/lncrnas/lncall?page=2
https://ngdc.cncb.ac.cn/lncbook/lncrnas/lncall?page=3
#為了一次獲取更多的數(shù)據(jù),避免頻繁獲取被封IP,我們可以修改size的數(shù)值,參數(shù)間使用【&】連接
https://ngdc.cncb.ac.cn/lncbook/lncrnas/lncall?page=3&size=50
  • 把連接粘貼到瀏覽器的地址欄中即可訪問,如下:
    JSON數(shù)據(jù)

2、開始爬取

  • 獲取到信息之后的事情就簡(jiǎn)單了,利用傳統(tǒng)的靜態(tài)爬蟲技術(shù)就可以訪問地址并獲取數(shù)據(jù)啦
  • 導(dǎo)入包
import json
import urllib.request,urllib.error
import re
import openpyxl
import time
  • 定義主函數(shù)
def main():
    baseurl = "https://bigd.big.ac.cn/lncbook/lncrnas/lncall?page="
    datalist = getData(baseurl)
    savepath = "lncrnas.xlsx"
    saveData(datalist,savepath)
  • 定義獲取網(wǎng)頁信息的函數(shù),其中稍微涉及一些正則表達(dá)式,需要理解一下
def getData(baseurl):
    datalist = []
    for i in range(0,27):
        #time.sleep(1)
        url = baseurl + str(i) + str("&size=10000")  #可以看到這里我設(shè)置的是10000,也就是一下獲取1w條數(shù)據(jù)
        html = askURL(url)
        data = re.findall("\"total\":268848,\"transInfo\":(.+?),\"page\"", str(html))
        jsonObj = json.loads(data[0])
        for item in jsonObj:
            items = [item['transid'], item['geneid'], item['chrome'],
                     item['startsite'], item['endsite'], item['strand'], item['length'],
                     item['exonNum'], item['orfLength'], item['gcContent'],item['classification']]
            datalist.append(items)
            #print(items)
        print("第%d頁已完成"%(i+1))
    return datalist
  • 定義保存數(shù)據(jù)的函數(shù)
def saveData(datalist,savepath):
    book = openpyxl.Workbook()
    sheet = book.create_sheet(title="lncrnas")
    col= ("Transcript ID","Gene ID","Chrome","Startsite","Endsite","Strand","Length (nt)","Exon Number","ORF Length (nt)","GC Content (%)","Classification")
    for i in range(0,11):
        sheet.cell(row = 1, column = i+1).value = col[i]
    for i in range(0,268848):
        print("第%d條已完成"%(i+1))
        data = datalist[i]
        for j in range(0,11):
            sheet.cell(row = i+1, column = j+1).value = data[j]
    print('正在保存')
    book.save(savepath)
  • 定義訪問URL的函數(shù)
def askURL(url):
    head = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36 Edg/89.0.774.57"}
    request = urllib.request.Request(url,headers=head)
    html=""
    try:
        response = urllib.request.urlopen(request)
        html= response.read().decode("utf-8")
        #print(html)
        pass
    except urllib.error.URLError as e:
        if hasattr(e,"code"):
            print(e.code)
        if hasattr(e,"reason"):
            print(e.reason)
            pass
        pass
    return html
  • 調(diào)用函數(shù)
if __name__ == "__main__":
    main()
    print('爬取結(jié)束')
  • 結(jié)果展示
爬取結(jié)果

寫在最后

  • 其實(shí)要想將上面的代碼化為己用還是挺頭痛的,因此如果你有這方面的需求又搞不定上面的代碼,我可以【有償】幫助你。(財(cái)迷本迷)


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

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

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