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

2023-11-06

测试网站: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)   #这里我并没有将第一层存入,而是直接以参数传入
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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

随机推荐