有时候网页会包含乱码导致xpath解析失败,百度或者谷歌了好久也没发现解决方法,最后只好自己写了一个替换方法,利用报错信息中的position剔除相应的数据。
方法如下
def remove_error_code(byte_string,charset):
for try_times in range(10):
try:
result = byte_string.decode(charset)
break
except Exception as e:
stre = str(e)
index = re.search('in position (\d+)',stre).group(0)
if index:
index=int(index)
byte_string=byte_string[:index]+byte_string[index+1:]
return result