python - 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
解决方案
这一行是错误的:
x = p.findall(r.text)[0].strip().replace('\r\n ','').replace('\xa0',' ').replace('\\','\\\\')
你需要在文本中找到什么?
对于在文本上刮擦的工作,您需要将上面的行更改为:
x = r.text.strip().replace('\r\n ','').replace('\xa0',' ').replace('\\','\\\\')
然后找到你需要的东西
推荐阅读
- python - python通信MODBUS TCP/IP树莓派和HMI-写值
- android - 在不触发发射的情况下插入 Android Room 表?
- dart - Dart 2 中可选关键字 new 的实用性
- python-3.6 - 使用 items() 方法的具有列表理解的 Python 最新打印格式
- python - CNN(Python Keras)的训练过程
- jquery - 访问受 EJS 保护的 JWT 路由
- protractor - E2E 最佳实践 - 等待页面上的元素
- c# - C#从form2更改按钮文本
- react-native - 使用 fetch 和 axios 无法在表单数据中使用 POST 服务时遇到麻烦.... 反应本机状态 406
- python - 如何在 semilogx 图中旋转次要刻度的轴标签?