【问题标题】:IndexError: list index out of range with Regular expressionIndexError:使用正则表达式列出超出范围的索引
【发布时间】:2019-10-03 15:06:35
【问题描述】:

我正在尝试从此链接中抓取数据 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

【问题讨论】:

  • list index out of range 表示索引有问题 [0] 所以首先检查你在 print( p.findall(r.text) ) 中的内容
  • 如果你得到p.findall(r.text) 的空列表,那么你可以检查r.text - 你可以将它保存在文件中并在网络浏览器中打开 - 也许有一些有用的信息或对机器人/脚本的警告或捕获。
  • 我运行代码,有时我得到带有文本 "Oops, une erreur technique est survenue. Merci de ressayer ultérieurement." 的页面,这意味着 "oops, a technical error has occurred. please try again later." and then findall()` 返回空列表 - 所以它没有索引 [1] 并且代码显示错误 list index out of range

标签: python regex web-scraping


【解决方案1】:

这一行是错误的:

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

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

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

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

然后找到你需要的东西

【讨论】:

  • 问题是有时页面显示消息“Oops, une erreur technology est survenue。Merci de ressayer ultérieurement。”意思是“糟糕,出现技术错误。请稍后重试。”然后findall() 找不到预期的文本。
【解决方案2】:

发生错误是因为有时没有匹配项,并且您试图访问空列表中不存在的项目。使用print(re.findall("s", "d")[0]) 可以重现相同的结果。

要解决此问题,请将x = p.findall(r.text)[0].strip().replace('\r\n ','').replace('\xa0',' ').replace('\\','\\\\') 行替换为

x = ''
xm = p.search(r.text)
if xm:
    x = xm.group(1).strip().replace('\r\n    ','').replace('\xa0',' ').replace('\\','\\\\')

注意事项

  • 当您使用p.findall(r.text)[0] 时,您希望获得输入中的第一个匹配项,因此这里最好使用re.search,因为它只返回第一个匹配项
  • 要获取第一个捕获组中捕获的substirng,需要使用matchObject.grou[p(1)
  • if xm: 很重要:如果没有匹配,x 将保持为空字符串,否则将在第 1 组中分配修改后的值。

【讨论】:

    猜你喜欢
    • 2011-10-31
    • 2015-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多