python爬取盤搜的有效鏈接實現(xiàn)代碼
因為盤搜搜索出來的鏈接有很多已經(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)載,煩請注明出處,謝謝!
- Python爬取APP下載鏈接的實現(xiàn)方法
- Python爬取京東的商品分類與鏈接
- Python3實現(xiàn)爬取簡書首頁文章標題和文章鏈接的方法【測試可用】
- 實例講解Python爬取網(wǎng)頁數(shù)據(jù)
- python爬取網(wǎng)站數(shù)據(jù)保存使用的方法
- Python實現(xiàn)爬取知乎神回復(fù)簡單爬蟲代碼分享
- python爬蟲實戰(zhàn)之爬取京東商城實例教程
- 以視頻爬取實例講解Python爬蟲神器Beautiful Soup用法
- Python實現(xiàn)爬取需要登錄的網(wǎng)站完整示例
- python制作爬蟲爬取京東商品評論教程
- python實現(xiàn)的爬取電影下載鏈接功能示例
相關(guān)文章
Python拋出引發(fā)異常(raise)知識點總結(jié)
在本篇文章里小編給大家整理了關(guān)于Python拋出引發(fā)異常(raise)知識點總結(jié)內(nèi)容,有需要的朋友們可以學(xué)習(xí)參考下。2021-06-06
python中的class_static的@classmethod的巧妙用法
python中的class_static的@classmethod的使用 classmethod的使用,主要針對的是類而不是對象,在定義類的時候往往會定義一些靜態(tài)的私有屬性,今天通過示例代碼看下classmethod的妙用2021-06-06

