首頁 > 軟體

Python非同步爬取知乎熱榜範例分享

2022-04-11 22:00:14

一、錯誤程式碼:摘要和詳細的url獲取不到

import asyncio
from bs4 import BeautifulSoup
import aiohttp
 
headers={
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
    'referer': 'https://www.baidu.com/s?tn=02003390_43_hao_pg&isource=infinity&iname=baidu&itype=web&ie=utf-8&wd=%E7%9F%A5%E4%B9%8E%E7%83%AD%E6%A6%9C'
}
async def getPages(url):
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.get(url) as resp:
            print(resp.status)  # 列印狀態碼
            html=await resp.text()
    soup=BeautifulSoup(html,'lxml')
    items=soup.select('.HotList-item')
    for item in items:
        title=item.select('.HotList-itemTitle')[0].text
        try:
            abstract=item.select('.HotList-itemExcerpt')[0].text
        except:
            abstract='No Abstract'
        hot=item.select('.HotList-itemMetrics')[0].text
        try:
            img=item.select('.HotList-itemImgContainer img')['src']
        except:
            img='No Img'
        print("{}n{}n{}".format(title,abstract,img))
 
if __name__ == '__main__':
    url='https://www.zhihu.com/billboard'
    loop=asyncio.get_event_loop()
    loop.run_until_complete(getPages(url))
    loop.close()

二、檢視JS程式碼

發現詳細連結、圖片連結、問題摘要等都在JS裡面(CSDN的開發者助手外掛確實好用)

正規表示式獲取上述資訊:

接下來就是詳細的程式碼啦

import asyncio
import json
import re
import aiohttp
 
headers={
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
    'referer': 'https://www.baidu.com/s?tn=02003390_43_hao_pg&isource=infinity&iname=baidu&itype=web&ie=utf-8&wd=%E7%9F%A5%E4%B9%8E%E7%83%AD%E6%A6%9C'
}
async def getPages(url):
    async with aiohttp.ClientSession(headers=headers) as session:
        async with session.get(url) as resp:
            print(resp.status)  # 列印狀態碼
            html=await resp.text()
 
    regex=re.compile('"hotList":(.*?),"guestFeeds":')
    text=regex.search(html).group(1)
    # print(json.loads(text))   # json換成字典格式
    for item in json.loads(text):
        title=item['target']['titleArea']['text']
        question=item['target']['excerptArea']['text']
        hot=item['target']['metricsArea']['text']
        link=item['target']['link']['url']
        img=item['target']['imageArea']['url']
        if not img:
            img='No Img'
        if not question:
            question='No Abstract'
        print("Title:{}nPopular:{}nQuestion:{}nLink:{}nImg:{}".format(title,hot,question,link,img))
 
if __name__ == '__main__':
    url='https://www.zhihu.com/billboard'
    loop=asyncio.get_event_loop()
    loop.run_until_complete(getPages(url))
    loop.close()

到此這篇關於Python非同步爬取知乎熱榜範例分享的文章就介紹到這了,更多相關Python非同步爬取內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com