小小小小面包 2024-06-02 16:30 采纳率: 100%
浏览 13
已结题

为什么我的python爬取内容只显示几条数据,如果可以,希望真人回答附改正解决代码

回答问题前可以先运行一遍我的代码在修改回答问题可以吗

import  requests
from  bs4  import   BeautifulSoup
import  pandas as  pd
import   time
def getUrls():
    urls=[]  
    baseUrl="https://cq.lianjia.com/ershoufang/"
    for i in range(1,101):  
           url="{}pg{}".format(baseUrl, i )
           urls.append(url)
    return urls


def gethtmltext(url):
    try:
        r=requests.get(url,timeout=30) 
        r.raise_for_status()
        return r.text
    except:
        return ""


def  ParsePage(html):
    soup = BeautifulSoup(html, features="html.parser")
    title = soup.select(".title a[data-el]")
    positionInfo = soup.select(".positionInfo")  
    houseInfo = soup.select(".houseInfo")  
    followInfo = soup.select(".followInfo")  
    totalPrice = soup.select(".totalPrice")  
    unitPrice = soup.select(".unitPrice") 
    tag = soup.find_all("div", attrs={"class": "tag"}) 
    count = len(title)  
    data = []
    for i in range(count):
        name = ""
        region = ""
        pos = str(positionInfo[i].text).split("-")
        if len(pos) == 2:  
            name = pos[0]
            region = pos[1]
      
        info = str(houseInfo[i].text).split("|")
        if len(info) != 7:
            break
        info[1] = float(info[1].replace("平米", "").strip())

        focus_num = ""   
        publish_time = "" 
        f_info= str(followInfo[i].text).split("/")
        if len(f_info)==2 :
            focus_num=f_info[0]
            publish_time= f_info[1]

        total=str(totalPrice[i].text)
        total= float(total.replace("万","").strip())

        unit = str(unitPrice[i].text)
        unit = unit.replace(",", "")
        unit = str(unit.replace("单价","").replace("元/平米","").strip())

        tag1 = tag[i].find_all("span")
        tags=""
        for t in tag1:
            tags += t.text+"   "
        data.append([title[i].text,name, region ,
              info[0],info[1],info[2],info[3],info[4],info[5],
              focus_num,publish_time,
              total,unit, tags  ])

    return data

head = []
df = pd.DataFrame(head, columns=["标题", "名称", "区域", "户型", "面积", "朝向", "装修", "楼层", "结构", "关注", "时间", "总价", "单价","标签"])
df.to_csv("data.csv", mode="a", header=True, index=False, encoding="utf-8")
x = getUrls() 
count =1
for i in x:  
    html =gethtmltext(i) 
    pagedata =ParsePage(html)  
    df= pd.DataFrame(pagedata)  
    df.to_csv("data.csv",mode="a",index=False,header=False, encoding="utf-8")  
    print("第{}页写入完毕!".format(count))
    time.sleep(3) 
    count+=1

img

img

只能保存画线处的6个以 “ | ” 切分的数据
5个的不行

  • 写回答

10条回答 默认 最新

  • svygh123 2024-06-02 18:15
    关注
    if len(info) != 7:
        break
    

    改为

    if len(info) != 7:
        info.append('')
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(9条)

报告相同问题?

问题事件

  • 系统已结题 6月10日
  • 已采纳回答 6月2日
  • 修改了问题 6月2日
  • 修改了问题 6月2日
  • 展开全部

悬赏问题

  • ¥15 这个如何解决详细步骤
  • ¥15 在微信h5支付申请中,别人给钱就能用我的软件,这个的所属行业是啥?
  • ¥30 靶向捕获探针设计软件包
  • ¥15 react-diff-viewer组件,如何解决数据量过大卡顿问题
  • ¥20 遥感植被物候指数空间分布图制作
  • ¥15 安装了xlrd库但是import不了…
  • ¥20 Github上传代码没有contribution和activity记录
  • ¥20 SNETCracker
  • ¥15 数学建模大赛交通流量控制
  • ¥15 为什么我安装了open3d但是在调用的时候没有报错但是什么都没有发生呢