嘗試創建一個可以從 Booking.com 獲取評論者姓名和評論的代碼。
我能夠獲得所有必要的 URL 并將審閱者的姓名和評論與 HTML 代碼隔離開來,但我正在努力創造一段時間來進行下一次審閱。
while 回圈應該將審閱者的姓名附加到串列中,移動到下一個姓名附加它等等。我也需要同樣的評論。
運行代碼時沒有任何反應,我不確定我的問題出在哪里。
#Loop parameters
##HTMLs
#Booking.com URL
search_url[0] = 'https://www.booking.com/reviews/us/hotel/shore-cliff.es.html?label=gen173nr-1DEgdyZXZpZXdzKIICOOgHSDNYBGiTAogBAZgBCrgBF8gBDNgBA-gBAYgCAagCA7gC5bPZkQbAAgHSAiQzMTc3NTA4OS00OGRkLTQ5ZjYtYjBhNi1kOWEzYzZhN2QwOWXYAgTgAgE;sid=3e3ae22b47e3df3ac2590eb19d37f888;customer_type=total;hp_nav=0;old_page=0;order=featuredreviews;page=1;r_lang=all;rows=75&'
link = search_urls[0] #Just the first one to try
url = link
html = urllib.request.urlopen(url).read().decode('utf-8') #loading each search page
#Main HTML of first hotel
index=html.find('')
review_list_html = html[index:]
##Lists:
hotels=[]
reviewer_name=[]
review_comment=[]
#Creating counter variable
counter=0
reviewercount =0
#Main HTML of first hotel
index=html.find('')
review_list_html = html[index:]
reviewer_html = review_list_html[review_list_html.find('reviewer_name'):]
review_html = review_list_html[review_list_html.find('>'):]
#Loop to get reviewer
while review_list_html.find('reviewer_name'):
#Get reviewer's name
#Start of reviewers name
start =reviewer_html.find('<span itemprop="name">') 22 #To ignore <span itemprop="name"> and jump right the name
start
#End of reviewers name
end =reviewer_html.find('</span>')
#Isolating reviewers name
reviewer_html=reviewer_html[start:end]
#Adding reviewer to list
reviewer_name.append(reviewer_html)
uj5u.com熱心網友回復:
您的問題是每次下一個索引查找都需要從上一個索引開始,否則您將創建永恒回圈。通常,使用Beautiful Soup之類的 HTML 決議器更為常見,但絕對可以使用您嘗試使用的方法決議此頁面。
我們可以將"reviewer_name"其用作每個評論塊的主要索引。從這個索引開始,我們將得到"name"和的索引</span>。這些索引之間的文本是審閱者的姓名。為了決議審查正文,我們將找到"reviewBody"下一個審查塊的索引之前的所有索引。
完整代碼:
from urllib.request import urlopen
link = "https://www.booking.com/reviews/us/hotel/shore-cliff.es.html"
with urlopen(link) as request:
response = request.read().decode()
reviews = []
name_pos = response.find('"reviewer_name"') # find first review
while name_pos >= 0:
name = ""
review_blocks = []
start_pos = response.find('"name"', name_pos)
end_pos = response.find("</span>", start_pos)
if end_pos > start_pos >= 0:
name = response[start_pos 7: end_pos]
prev_name_pos = name_pos
name_pos = response.find('"reviewer_name"', name_pos 1) # get next review
start_pos = response.find('"reviewBody"', prev_name_pos, name_pos)
while start_pos >= 0:
end_pos = response.find("</span>", start_pos)
if end_pos > start_pos >= 0:
review_blocks.append(response[start_pos 13: end_pos])
start_pos = response.find('"reviewBody"', start_pos 1, name_pos)
reviews.append((name, "\n".join(review_blocks)))
reviews內容:
[
('Adriana',
'Nada para criticar.\n'
'Impecable lugar, habitación con vistas hermosas cualquiera sea. Camas '
'confortables, peque?a cocina completa, todo impecable.\n'
'La atención en recepción excelente, no se pierdan las cookies que convidan '
'por la tarde allí. El desayuno variado y con unos tamales exquisitos! Cerca '
'de todo.'),
('Ana', 'Todo excelente'),
('Lara',
'simplemente un poco de ruido en el tercer piso pero solo fue un poco antes '
'de las 10:00pm\n'
'realmente todo estaba excelente, ese gran detalle de el desayuno se les '
'agradece mucho.'),
('Rodrigo',
'Todo me gustó solo lo único que me hubiera gustado que también tuvieran es '
'unas chimeneas.\n'
'El hotel tiene una hermosa vista y se puede caminar y disfrutar por toda la '
'orilla de la playa hasta llegar al muelle y mas lejos si uno quiere.'),
('May', 'Me encanto q estaba abierta la piscina ????el mar expectacular'),
('Scq', 'Las vistas al Pacífico'),
('Eva', 'Desayuno\nUbicación y limpieza'),
('Marta',
'Muy buena ubicación y vistas al mar. Habitaciones modernas, amplias y con '
'cocina. Buen desayuno y hasta las 10, a diferencia de otros hoteles en los '
'que estuvimos. Personal muy amable. El chek out es a las 12 por lo que te '
'permite disfrutar de las piscina y de las vistas y paseo por la costa.'),
('Filippo',
'Habitación enorme, y muy limpio. \n'
'La habitación con vista al Ocean .... top'),
('Enrique', 'La atención del personal'),
('Lucia',
'El lugar para el desayuno es demasiado peque?o y no hay lugar suficiente '
'para sentarse\n'
'La vista, los jardines y todo el entorno son preciosos. Y es muy '
'confortable!'),
('Pablo', 'El precio.\nLa ubicación y el desayuno'),
('Walter', 'El hotel está bien, la ubicación es buena'),
('Anónimo', 'Muy bueno, el personal muy amable\nExcelente lugar muy cómodo'),
('Gonzalo', ''),
('Maria', ''),
('Rosana', ''),
('Leticia', ''),
('María', ''),
('Samantha', '')
]
你可以幫助我的國家,查看我的個人資料資訊。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/446190.html
