【发布时间】:2020-02-07 19:31:50
【问题描述】:
我正在尝试使用 BeautifulSoup 抓取动态页面。在 Selenium 的帮助下从https://www.nemlig.com/ 访问上述页面后(感谢@cruisepandey 的代码建议),如下所示:
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from bs4 import BeautifulSoup
driver = webdriver.Chrome(executable_path = r'C:\Users\user\lib\chromedriver_77.0.3865.40.exe')
wait = WebDriverWait(driver,10)
driver.maximize_window()
driver.get("https://www.nemlig.com/")
wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, ".timeslot-prompt.initial-animation-done")))
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "input[type='tel'][class^='pro']"))).send_keys('2300')
wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, ".btn.prompt__button"))).click()
系统提示我要抓取此页面。
更准确地说,此时,我想从页面的右侧刮掉行。如果您查看这些背后的 HTML 代码,您会注意到 div 类 time-block__row 在一天中的主要 3 次具有 3 个不同的数据自动化属性。
<div class="time-block__row" data-automation="beforDinnerRowTmSlt">
<div class="time-block__row-header">Formiddag</div>
<div class="no-timeslots ng-hide" ng-show="$ctrl.timeslotDays[$ctrl.selectedDateIndex].morningHours == 0">
Ingen levering..
</div>
<!----><!----><div class="time-block__item duration-1 disabled" ng-repeat="item in $ctrl.selectedHours track by $index" ng-if="item.StartHour >= 0 && item.StartHour < 12" ng-click="$ctrl.setActiveTimeslot(item, $index)" ng-class="['duration-1', {'cheapest': item.IsCheapHour, 'event': item.IsEventSlot, 'selected': $ctrl.selectedTimeId == item.Id || $ctrl.selectedTimeIndex == $index, 'disabled': item.isUnavailable()}]" data-automation="notActiveSltTmSlt">
<div class="time-block__inner-container">
<div class="time-block__time">8-9</div>
<div class="time-block__attributes">
<!----></div>
<div class="time-block__cost">29 kr.</div>
所以Formiddag(早上)有data-automation = "beforDinnerRowTmSlt",Eftermiddag(下午)有data-automation = "afternoonRowTmSlt",Aften(晚上)有@987654329 @。
page_source = wait.until(driver.page_source)
soup = BeautifulSoup(page_source)
time_of_the_day = soup.find('div', class_='time-block__row').text
- 问题是
使用上面的代码,time_of_the_day 仅包含来自 Morning 行的信息。
如何使用data-automation 属性正确抓取这些行?我怎么可能访问其他 2 个 div 类及其子 div?我的计划是创建一个包含以下内容的数据框:
Time_of_the_day Hours Price Day
Formiddag 8-9 29kr. Tor. 10/10
.... .... .... ....
Eftermiddag 12-13 29kr. Tor. 10/10
.... .... .... ....
day 列将包含此处的输出:day = soup.find('div', class_='content').text
我知道这是一篇很长的帖子,但希望我已经使任务变得容易理解,并且您将能够帮助我提供建议、提示或代码!
【问题讨论】:
标签: python html web-scraping beautifulsoup