老孙的爬虫(四)-------储存多层次的数据,使用递归不断请求,设置id与p_id确定数据的父子关系

测试网站:https://d.qianzhan.com/xdata/list/xfyyy0yyIxPyywyy2xDxfd.html

数据的储存要求:储存的数据能看出父子关系

思路:因为该网站数据是层层打开的,使用递归不断请求。需要额外储存一些数据来区分数据的层次以及关系。例子:假设a数据id为1,则在a数据的子数据的p_id就都用a的id  1.

代码如下:

from pymongo import MongoClient
import requests
from lxml import etree
from Ip_and_Agent.ip_and_Agent import User_Agent,Inland_ip

con=MongoClient("localhost",27017)
db=con.Runoob
my_set=db.qianzhan_set6

#get_html()方法封装的是requests请求,里面的Inland_ip是我随机取出单独封装的国内ip,User_Agent()是随机表头

def get_html(url): 
    req=requests.get(url,proxies={"http":Inland_ip},headers={"User_Agent":User_Agent})
    # print(req.text)
    return req.text

#从存入到mongodb的数据中取出,取出后修改状态

def get_key():
    get_key = my_set.find_one_and_update({"state": 0}, {"$set": {"state": 1}})
    return get_key
#大致思路就是,把从第一个传入的参数作为第0层,然后将获取的第一层数据定义为第一层(即level为1),并且各个数据的id为1。然后只要是从第一层里取出的url再次放入函数中取值,把第一层存放的id作为第二层的p_id,这样根据id和p_id区分父子关系
id = 0
def get_data(url,level,p_id):
    global id
    # for index in range(1, 10):
    # for url in recover_url(url_list):
    print("url:   ",level,url)
    text = get_html(url)
    html = etree.HTML(text)
    my_title = html.xpath("//div[@class='searchfilter_sub']["+str(level)+"]/a/text()")[1:]
    my_url = html.xpath("//div[@class='searchfilter_sub']["+str(level)+"]/a/@href")[1:]
    # my_set.update({"title":my_title,"url":my_url,"next_title":[{}]})

    if my_title==[]:
        data_title=html.xpath("//div/table/tbody/tr/td[1]/a/text()")
        data_url=html.xpath("//div/table/tbody/tr/td[1]/a/@href")
        try:
            for title2 in data_title:
                id += 1
                my_set.insert_one({"id": id, "p_id": p_id, "title": title2, "url": "https://d.qianzhan.com"+my_url[1], "level": level + 1, "state": 0})
                print(data_url)
        except:
            pass
        return
    else:
        # pass
        print("my_title:",my_title)
        index=0
        for title in my_title:
            id+=1
            print("id:",id)
            my_set.insert_one({"id":id,"p_id":p_id,"title":title,"url":"https://d.qianzhan.com"+my_url[index],"level":level,"state":0})
            index += 1
            # get_data=my_set.find_one_and_update({"state":0},{"$set":{"state":1}})
            data=get_key()
            new_level=data["level"]+1
            new_url=data["url"]
            new_id=data["id"]
            print(new_id,new_url,new_level)
            get_data(new_url,new_level,new_id)
            # print(index,my_title )

get_data("https://d.qianzhan.com/xdata/list/xfyyy0yyIxPyywyy2xDxfd.html",1,0)   #这里我并没有将第一层存入,而是直接以参数传入
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值