首页 > 解决方案 > 使用beautifulsoup抓取时无法获取所有数据

问题描述

我正在练习使用 selenium 和 beautifulsoup 来抓取我当地的电子商务网站。但是当我尝试运行代码时,我只获得了一些价值,而其余的我就无法获得它。

import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import requests, time

option = Options()

option.add_argument("--disable-infobars")
option.add_argument("--disable-extensions")

# block any notification
option.add_experimental_option("prefs", {
    "profile.default_content_setting_values.notifications": 2
})

driver = webdriver.Chrome(options=option, executable_path=os.path.abspath('chromedriver'))
driver.get('https://www.tokopedia.com/')

# click the action-figure category
driver.find_element_by_css_selector('.css-15j6m2y > div:nth-child(5) > div:nth-child(1) > div:nth-child(1) > a:nth-child(1)').click()

page = driver.page_source

driver.quit()

soup = BeautifulSoup(page, 'html.parser')

container = soup.find_all('div', attrs={'class': 'css-bk6tzz e1nlzfl3'})

for count, action in enumerate(container, 1):
    name = action.find('span', class_='css-1bjwylw').text
    price = action.find('span', class_='css-o5uqvq').text
    print('-------')
    print(count)
    print(f'nama: {name}')
    print(f'harga: {price}')

我没有收到任何错误,但是脚本以某种方式结束而没有获取所有数据。我的方法有错误吗?

PS这是我在StackOverflow中的第一个问题,我做得对吗?提前致谢。

标签: pythonseleniumweb-scrapingbeautifulsoup

解决方案


我已经找到了问题,感谢 PApostol 询问班级名称。

问题是,在用户向下滚动页面之前,该页面不会加载所有产品。它只显示前 10 个项目。在我尝试向下滚动之后,我得到了所有的价值。

添加这一行,滚动到页面底部。

driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

我的代码现在看起来像这样:

import os
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import requests, time

option = Options()

option.add_argument("--disable-infobars")
option.add_argument("--disable-extensions")

# block any notification
option.add_experimental_option("prefs", {
    "profile.default_content_setting_values.notifications": 2
})

driver = webdriver.Chrome(options=option, executable_path=os.path.abspath('chromedriver'))
driver.get('https://www.tokopedia.com/')

# click the action-figure category
driver.find_element_by_css_selector('.css-15j6m2y > div:nth-child(5) > div:nth-child(1) > div:nth-child(1) > a:nth-child(1)').click()

# to scroll to the bottom of the page.
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")

time.sleep(10)

page = driver.page_source

soup = BeautifulSoup(page, 'html.parser')

container = soup.find_all('div', attrs={'class': 'css-bk6tzz e1nlzfl3'})

for count, action in enumerate(container, 1):
    name = action.find('span', class_='css-1bjwylw').text
    price = action.find('span', class_='css-o5uqvq').text
    print('-------')
    print(count)
    print(f'nama: {name}')
    print(f'harga: {price}')

我将其更改driver.quit()time.sleep(20)因为获得所有产品需要时间。


推荐阅读