【发布时间】: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 thenfindall()` 返回空列表 - 所以它没有索引[1]并且代码显示错误list index out of range
标签: python regex web-scraping