首页 > 编程语言 >Python 获取并分析均价思路

Python 获取并分析均价思路

时间:2023-01-08 14:02:14浏览次数:39  
标签:均价 head Python text pd1 len print 思路 div

1、思路:分析网页,是静态网页后,用requests 建立解析。
2、步骤:
--建立headers 方法
--拼接start-URL,
--构件程序控制函数main控制运行,这里代码很少,其实不用的。
--requests循环发送请求解析
--pandas进行拼接和保存。
3、pandas分析另外贴,本来用图标的。想要的内容太多所以表格看看就好了
4、此文作为备忘

点击查看代码

构建headers

def header():
    head = {
        'User-Agent': '换成自己的',
        'cookie':'csrf=网站上的cookie这里少了部分BRU5NWndQRUoo2PmcGtNomy7Ihsj4ODie53NijgWv2yGmAm2LdW9UuA%3D%3D,hj_house=cf574216ec8c0fa66d4152'
    }
    # cookie = requests.get(url=starturl1).cookies
    return head
点击查看代码
拼接所有的URL

def starturl():
    starturl1 = ['https://www.xxx.com/resoldhome/esf/list']
    nexturl= ['https://www.xxx.com/resoldhome/esf/list?page='+str(x) for x in range(2,16)]
    for i in nexturl:starturl1.append(i)
    return starturl1
点击查看代码
请求并解析。

def res(starturl,head):
    date= {}#建立字典为pandas做准备
    age = 1#计数器
    e,f =[],[]#储存小区和价格的容器
    for i in starturl:#循环地址,这里可以用切片器指定页面
        time.sleep(3)#每循环一次暂停3秒
        res1 = requests.get(url=i,headers=head)#发请求
        if res1.status_code==200:#判断是否响应成功
            a = etree.HTML(res1.text)
            c = a.xpath('/html/body/div[6]/div[3]/ul//li/div[2]/div[2]/p/em/text()')#面议
            aa = [i for i,x in enumerate(c)if x =="面议"]#找到‘面议“的位置,插入获取不到的每平方价格
            b = a.xpath('/html/body/div[6]/div[3]/ul//li/div[2]/div[2]/p[2]/text()')#每平方价格
            d = a.xpath('/html/body/div[6]/div[3]/ul//li/div[2]/p[3]/a[1]/text()')#小区
            for h in reversed(aa):
                d.pop(h)
                print(f"在{h}位置删除面议")
            for i in d:e.append(i)
            for g in b:
                f.append(g.replace("元/㎡","")) #替换单位,只要数据就行。
            age+=1
        print(f"第{age}页!")
    print(len(e),len(f))
    date["小区"]=e#构建字典
    date["价格"]=f
    # print(len(e),len(f))检查小区和价格数量是否一致,不一致是构件pandas会报错
    time.sleep(1)
  #用pandas 转存csv格式。
    pd1 = pd.DataFrame(date)
    print(pd1.head(5))
    pd1.to_csv('./小区价格.csv')   # os.system("pause")调试用,可以暂停程序
点击查看代码
完整代码
import requests
from lxml import etree
import time
import pandas as pd
def res(starturl,head):
    date= {}
    age = 1
    e,f =[],[]
    for i in starturl:
        time.sleep(3)
        res1 = requests.get(url=i,headers=head)
        if res1.status_code==200:
            a = etree.HTML(res1.text)
            c = a.xpath('/html/body/div[6]/div[3]/ul//li/div[2]/div[2]/p/em/text()')#面议
            aa = [i for i,x in enumerate(c)if x =="面议"]#找到‘面议“的位置,插入获取不到的每平方价格
            b = a.xpath('/html/body/div[6]/div[3]/ul//li/div[2]/div[2]/p[2]/text()')#每平方价格
            d = a.xpath('/html/body/div[6]/div[3]/ul//li/div[2]/p[3]/a[1]/text()')#小区
            for h in reversed(aa):
                # print(h)
                d.pop(h)
                print(f"在{h}位置删除面议")
            for i in d:e.append(i)
            # print(aa,type(b))
            for g in b:
                f.append(g.replace("元/㎡","")) 
            age+=1
            time.sleep(0)
        print(f"第{age}页!")
    print(len(e),len(f))
    date["小区"]=e
    date["价格"]=f
    # print(len(e),len(f))
    time.sleep(1)
    pd1 = pd.DataFrame(date)
    print(pd1.head(5))
    pd1.to_csv('./小区价格.csv')   # os.system("pause")调试用,可以暂停程序
def starturl():
    starturl1 = ['https://www.xxx.com/resoldhome/esf/list']
    nexturl= ['https://www.xxx.com/resoldhome/esf/list?page='+str(x) for x in range(2,16)]
    for i in nexturl:starturl1.append(i)
    return starturl1
def header():
    head = {
        'User-Agent': '换成自己的',
        'cookie':'csrf=网站上的cookie这里少了部分BRU5NWndQRUoo2PmcGtNomy7Ihsj4ODie53NijgWv2yGmAm2LdW9UuA%3D%3D,hj_house=cf574216ec8c0fa66d4152'
    } 
    # cookie = requests.get(url=starturl1).cookies
    return head
def main():
    res(starturl(),header()) 
if __name__=="__main__":
    main()
点击查看代码 上面执行完之后,另建.py 文件。解析并保存Excel
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
pd1 =pd.read_csv("小区价格.csv",index_col=1)
pd2 = pd1.groupby("小区")["价格"].mean().round(0).sort_values(ascending=False)
pd2.to_excel("小区均价排行.xlsx",sheet_name="排行",index=True)
print(pd2.to_string())

标签:均价,head,Python,text,pd1,len,print,思路,div
From: https://www.cnblogs.com/wddzb/p/17034592.html

相关文章