手撸一个夸克盘搜索工具,你也可以(二)

710 阅读2分钟

如果没看过第一篇,链接 手撸一个夸克盘搜索工具,你也可以(一)

代码地址

github.com/ghjkg546/qu…

这一节来讲引擎数据的爬取

在谷歌搜索夸克资源分享,你能找到大量的类似这种网站

image.png

这种都是用一个基于php的论坛系统flarum搭建的,费用有利于爬取

打开F12,点击列表页的”加载更多“按钮

出现了这条请求,复制他的url

image.png

编写获取页面信息函数,仔细观察加载更多触发的接口,发现就是offset每次增加20,于是offset依次增加20,爬取每个url api下的标题和id

for i in range(2,1000):
    print("爬取接口"+str(limit*i))
    # 目标网页URL
    baseUrl = baseUrl+'/api/discussions?include=user%2ClastPostedUser%2Ctags%2Ctags.parent%2CfirstPost&sort&page%5Boffset%5D='+str(limit*i)
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36"
    }

    response = requests.get(baseUrl,headers=headers)
    res = response.text
    res_content = json.loads(res)
    data = res_content['data']

    for b in data:
        print(b['attributes']['title'])
        #随便点进一个文章,发现详情页的格式都是 baseUrl/d/:id,按照这个格式访问详情页。
        detail_url = baseUrl+"/d/"+b['id']
        getPageContent(b['attributes']['title'],detail_url)
        time.sleep(5)

提取页面详细信息的函数,因为搜索结果需要的是资源的标题和链接,这里我就取了这2个信息

#提取页面详细信息的函数
def getPageContent(title,url1):
    response = requests.get(url1)
    soup = BeautifulSoup(response.text, 'html.parser')
    div = soup.find('div', class_='Post-body')
    a_tags = div.find_all('a')
    a_str =""
    # 查找class为'Post-body'下的所有a标签,获取它们的href属性
    for a in a_tags:
        if a is not None:
            linkUrl = a.get('href')
            if(linkUrl is not None):
                a_str+=linkUrl
                print(a.get('href'))
    if a_str != "":
        postToManti(title,a_str)

提交数据到manti的函数

#提交数据到manti
def postToManti(title,link):
   url = "http://localhost:9308/sql"
   headers = {
       'Content-Type': 'application/json'
   }

   data = {
       "mode": "raw",
       "query": f"INSERT INTO resource_item (title, url, create_time) VALUES ( '{title}','{link}','{curTime}');"
   }
   response = requests.post(url, headers=headers, data=data)

注意

部分页面设置了回复可见,可自行F12观察回复可见调用什么接口,爬取前先调用下,之类就不实现了,爬取不到链接的页面我就跳过了