因為盤搜搜索出來的鏈接有很多已經(jīng)失效了,影響找數(shù)據(jù)的效率,因此想到了用爬蟲來過濾出有效的鏈接,順便練練手~
這是本次爬取的目標網(wǎng)址http://www.pansou.com,首先先搜索個python,之后打開開發(fā)者工具,
可以發(fā)現(xiàn)這個鏈接下的json數(shù)據(jù)就是我們要爬取的數(shù)據(jù)了,把多余的參數(shù)去掉,
剩下的鏈接格式為http://106.15.195.249:8011/search_new?q=python&p=1,q為搜索內(nèi)容,p為頁碼
以下是代碼實現(xiàn):
import requests import json from multiprocessing.dummy import Pool as ThreadPool from multiprocessing import Queue import sys headers = { "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36" } q1 = Queue() q2 = Queue() urls = [] # 存取url列表 # 讀取url def get_urls(query): # 遍歷50頁 for i in range(1,51): # 要爬取的url列表,返回值是json數(shù)據(jù),q參數(shù)是搜索內(nèi)容,p參數(shù)是頁碼 url = "http://106.15.195.249:8011/search_new?&q=%s&p=%d" % (query,i) urls.append(url) # 獲取數(shù)據(jù) def get_data(url): print("開始加載,請等待...") # 獲取json數(shù)據(jù)并把json數(shù)據(jù)轉(zhuǎn)換為字典 resp = requests.get(url, headers=headers).content.decode("utf-8") resp = json.loads(resp) # 如果搜素數(shù)據(jù)為空就拋出異常停止程序 if resp['list']['data'] == []: raise Exception # 遍歷每一頁數(shù)據(jù)的長度 for num in range(len(resp['list']['data'])): # 獲取百度云鏈接 link = resp['list']['data'][num]['link'] # 獲取標題 title = resp['list']['data'][num]['title'] # 訪問百度云鏈接,判斷如果頁面源代碼中有“失效時間:”這段話的話就表明鏈接有效,鏈接無效的頁面是沒有這段話的 link_content = requests.get(link, headers=headers).content.decode("utf-8") if "失效時間:" in link_content: # 把標題放進隊列1 q1.put(title) # 把鏈接放進隊列2 q2.put(link) # 寫入csv文件 with open("wangpanziyuan.csv", "a+", encoding="utf-8") as file: file.write(q1.get()+","+q2.get() + "\n") print("ok") if __name__ == '__main__': # 括號內(nèi)填寫搜索內(nèi)容 get_urls("python") # 創(chuàng)建線程池 pool = ThreadPool(3) try: results = pool.map(get_data, urls) except Exception as e: print(e) pool.close() pool.join() print("退出")
總結(jié)
以上所述是小編給大家介紹的python爬取盤搜的有效鏈接實現(xiàn)代碼希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復(fù)大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
