python xpath索引器错误:列表索引超出范围
我通过xpath从url源页面获取一个值。但这是不存在的。所以我想传递请求并再次尝试获取该值:我尝试的:python xpath索引器错误:列表索引超出范围,python,list,exception,if-statement,try-except,Python,List,Exception,If Statement,Try Except,我通过xpath从url源页面获取一个值。但这是不存在的。所以我想传递请求并再次尝试获取该值:我尝试的: import requests from lxml import html url='http://www.example.com' cont=requests.get(url) tree=html.fromstring(cont) out=tree.xpath('...')[0] 当我运行它时,出现以下错误: IndexError: list index out of range 在这
import requests
from lxml import html
url='http://www.example.com'
cont=requests.get(url)
tree=html.fromstring(cont)
out=tree.xpath('...')[0]
当我运行它时,出现以下错误:
IndexError: list index out of range
在这种情况下,如何再次请求获取值
使现代化
我知道这个错误意味着xpath不存在。所以我想请求该url再次获取xpath。使用Try-Except
import requests
from lxml import html
def do_get(xpath): # OR URL What ever you need
url='http://www.example.com'
cont=requests.get(url)
tree=html.fromstring(cont)
out=tree.xpath(xpath)[0]
try:
do_get('....')
except:
do_get('....')
或者,如果你想永远这样做,直到找到合适的人选:
def do_get(xpath):
url='http://www.example.com'
cont=requests.get(url)
tree=html.fromstring(cont)
out=tree.xpath(xpath)[0]
while True:
try:
do_get('....')
break
except:
pass
可能xpath不存在。我知道..是的xpath不存在。。所以我想再次请求url,如果它不是existed@MortezaLSC尝试一下除了???@Vincent Beltman谢谢你。。。你能通过修改代码来回答更详细的问题吗?