検索クエリから返されたHTMLコードの結果の数を解析しようとしていますが、find / index()を使用すると、間違った位置が返されるようです。検索している文字列にはアクセントがあるので、Unicode形式で検索してみます。
解析されるHTMLコードのスニペット:
<div id="WPaging_total">
Aproximádamente 37 resultados.
</div>
そして私はこのようにそれを検索します:
str_start = html.index(u'Aproxim\xe1damente ')
str_end = html.find(' resultados', str_start + 16)#len('Aproxim\xe1damente ')==16
print html[str_start+16:str_end] #works by changing 16 to 24
printステートメントは次を返します。
damente 37
期待される結果が次の場合:
37
str_startは、検索している文字列の先頭から始まっているのではなく、8桁後ろから始まっているようです。
print html[str_start:str_start+5]
出力:
l">
ただし、コードスニペットを使用する場合は発生せず、HTML文字列全体を検索する場合にのみ発生するため、問題を再現するのは困難です。str_start+16をstr_start+24に変更するだけで、意図したとおりに機能させることができますが、それでは問題を理解するのに役立ちません。Unicodeの問題ですか?うまくいけば、誰かがこの問題に光を当てることができます。
ありがとうございました。
リンク: http: //guiasamarillas.com.mx/buscador/?actividad = Chedraui&localidad =&id_page = 1
サンプルコード:
from urllib2 import Request, urlopen
url = 'http://guiasamarillas.com.mx/buscador/?actividad=Chedraui&localidad=&id_page=1'
post = None
headers = {'User-Agent':'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2)'}
req = Request(url, post, headers)
conn = urlopen(req)
html = conn.read()
str_start = html.index(u'Aproxim\xe1damente ')
str_end = html.find(' resultados', str_start + 16)
print html[str_start+16:str_end]