评论部分显示在 html 中,直到您单击 read more,它实际上不会进行 Ajax 调用,而是根据 window.__WEB_CONTEXT__ 中包含的数据更新页面。您可以通过查看它所在的 <script> 标记来访问此数据:
<script>
window.__WEB_CONTEXT__={pageManifest:{"assets":["/components/dist/@ta/platform.polyfill.084d8cdf5f.js","/components/dist/runtime.56c5df2842.js", .... }
</script>
一旦你得到它,你和你就可以提取和处理 JSON 格式的数据。完整代码如下:
import json
from bs4 import BeautifulSoup
resp = requests.get('https://www.tripadvisor.com.ph/Hotel_Review-g8762949-d1085145-Reviews-El_Rio_y_Mar_Resort-San_Jose_Coron_Busuanga_Island_Palawan_Province_Mimaropa.html#REVIEWS')
data = BeautifulSoup(resp.content).find('script', text = re.compile('window.__WEB_CONTEXT__')).text
#Some text processing to make the tag content a valid json
pageManifest = json.loads(data.replace('window.__WEB_CONTEXT__=','').replace('{pageManifest:', '{"pageManifest":')[:-1])
for x in pageManifest['pageManifest']['apolloCache']:
try:
reviews = x['result']['locations'][0]['reviewList']['reviews']
except:
pass
print([x['text'] for x in reviews])
输出
['Do arrange for airport transfers! From the airport, you will be taking a van for around 20 minutes, then you\'ll be transferred to a banca/boat for a 25 minute ride to the resort. Upon arrival, you\'ll be greeted by a band that plays their "welcome, welcome" song and in our case, we were met by Maria (awesome gal!) who introduced the group to the resort facilities and checks you in at the bar.I booked a deluxe room, which is actually a duplex with 2 adjoining rooms, ideal
for families, which accommodates 4 to a room.Rooms are clean and bed is comfortable.Potable water is provided upon check in , but is chargeable thereafter.Don\ 't worry, ...FULL REVIEW...',
"Stayed with my wife and 2 children, 10y and 13y. ...FULL REVIEW...",
'Beginning at now been in Coron for a couple of ...FULL REVIEW...',
'This was the most beautiful and relaxing place ...FULL REVIEW...',
'We spent 2 nights at El rio. It was incredible, ...FULL REVIEW... ']