【发布时间】:2020-01-03 08:35:37
【问题描述】:
在https://www.comparis.ch/carfinder/default 下输入的某些搜索查询会产生超过 1000 个结果(在搜索页面上动态显示)。然而,结果最多只显示 100 页,每页有 10 个结果,所以我试图在给定产生超过 1'000 个结果的查询的情况下抓取剩余的数据。 抓取前 100 个页面的 ID 的代码是(运行所有 100 个页面大约需要 2 分钟):
from bs4 import BeautifulSoup
import requests
# as the max number of pages is limited to 100
number_of_pages = 100
# initiate empty dict
car_dict = {}
# parse every search results page and extract every car ID
for page in range(0, number_of_pages + 1, 1):
newest_secondhand_cars = 'https://www.comparis.ch/carfinder/marktplatz/occasion'
newest_secondhand_cars = requests.get(newest_secondhand_cars + str('?page=') + str(page))
newest_secondhand_cars = newest_secondhand_cars.content
soup = BeautifulSoup(newest_secondhand_cars, "lxml")
for car in list(soup.find('div', {'id': 'cf-result-list'}).find_all('h2')):
car_id = int(car.decode().split('href="')[1].split('">')[0].split('/')[-1])
car_dict[car_id] = {}
所以我显然尝试只传递一个大于 100 的 str(page),这不会产生额外的结果。
如果有的话,我如何访问剩余的结果?
【问题讨论】:
-
有时这些结果会在浏览器中使用 javascript 加载,这意味着您必须解决这个问题。您能否通过查看浏览器中的结果来验证这没有发生。
-
页面上的实际结果在 id 为“result_list_ajax_container”的 div 中,这表明它们是动态加载的。您对此有何猜测?
-
我同意。这似乎表明结果是在浏览时在客户端加载的。你需要的是 Scrapy-Splash。它充当将呈现任何 javascript 的客户端,然后您从该客户端抓取。如果您知道如何使用 docker,这可能是最简单的入门方法:github.com/scrapy-plugins/scrapy-splash
标签: python web-scraping beautifulsoup