我正在尝试使用硒和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}')
我没有收到任何错误,但是该脚本以某种方式在没有获取所有数据的情况下结束了。我的方法有误吗?
P.S,这是我在StackOverflow中的第一个问题,我做对了吗?预先感谢。
答案 0 :(得分:0)
我已经发现了问题,感谢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)
,因为获取所有产品需要时间。