首页 > 解决方案 > IndexError:使用正则表达式列出超出范围的索引

问题描述

我正在尝试从此链接 https://www.seloger.com/抓取数据, 但出现此错误,我不明白出了什么问题,因为我之前已经尝试过此代码并且它有效

import re
import requests
import csv
import json


with open("selog.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["id", "Type", "Prix", "Code_postal", "Ville", "Departement", "Nombre_pieces", "Nbr_chambres", "Type_cuisine", "Surface"]) 


for i in range(1, 500):
   url = str('https://www.seloger.com/list.htm?tri=initial&idtypebien=1,2&pxMax=3000000&div=2238&idtt=2,5&naturebien=1,2,4&LISTING-LISTpg=' + str(i))
   r = requests.get(url, headers = {'User-Agent' : 'Mozilla/5.0'})
   p = re.compile('var ava_data =(.*);\r\n\s+ava_data\.logged = logged;', re.DOTALL)
   x = p.findall(r.text)[0].strip().replace('\r\n    ','').replace('\xa0',' ').replace('\\','\\\\')
   x = re.sub(r'\s{2,}|\\r\\n', '', x)
   data = json.loads(x)
   f = csv.writer(open("Seloger.csv", "wb+"))


   for product in data['products']:
      ID = product['idannonce']
      prix = product['prix']
      surface = product['surface']
      code_postal = product['codepostal']
      nombre_pieces = product['nb_pieces']
      nbr_chambres = product['nb_chambres']
      Type = product['typedebien']
      type_cuisine = product['idtypecuisine']
      ville = product['ville']
      departement = product['departement']
      etage = product['etage']
      writer.writerow([ID, Type, prix, code_postal, ville, departement, nombre_pieces, nbr_chambres, type_cuisine, surface])

这是错误:

Traceback (most recent call last):
File "Seloger.py", line 20, in <module>
x = p.findall(r.text)[0].strip().replace('\r\n    ','').replace('\xa0',' ').replace('\\','\\\\')
IndexError: list index out of range

标签: pythonregexweb-scraping

解决方案


这一行是错误的:

x = p.findall(r.text)[0].strip().replace('\r\n    ','').replace('\xa0',' ').replace('\\','\\\\')

你需要在文本中找到什么?

对于在文本上刮擦的工作,您需要将上面的行更改为:

x = r.text.strip().replace('\r\n    ','').replace('\xa0',' ').replace('\\','\\\\')

然后找到你需要的东西


推荐阅读