【发布时间】:2019-09-23 10:37:02
【问题描述】:
我有一个代码可以在 python 中抓取酒店评论(来自 yelp)。
代码完美地抓取了评论的第一页,但是,我正在努力抓取下一页。
While循环不起作用,每次循环抓取的数据都是一样的(第一页的数据)
import requests
from lxml import html
from bs4 import BeautifulSoup
url = 'https://www.yelp.com/biz/fairmont-san-francisco-san-francisco?sort_by=rating_desc'
while url:
r = requests.get(url)
t = html.fromstring(r.content)
for i in t.xpath("//div[@class='review-list']/ul/li[position()>1]"):
rev = i.xpath('.//p[@lang="en"]/text()')[0].strip()
date = i.xpath('.//span[@class="rating-qualifier"]/text()')[0].strip()
stars = i.xpath('.//img[@class="offscreen"]/@alt')[0].strip().split(' ')[0]
print(rev)
print(date)
print(stars)
next_page = soup.find('a',{'class':'next'})
if next_page:
url = next_page['href']
else:
url = None
sleep(5)
这里 sleep(5) 在请求新 url 之前是为了避免网站设置的限制。
【问题讨论】:
标签: python web-scraping beautifulsoup python-requests lxml