【发布时间】:2018-08-17 05:00:39
【问题描述】:
我正在尝试抓取此页面:https://redmart.com/fresh-produce/fresh-vegetables。但我面临的问题是它只返回一些元素。 我使用的代码如下:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium import webdriver
# Start the WebDriver and load the page
wd = webdriver.Chrome(executable_path=r"C:\Chrome\chromedriver.exe")
wd.get('https://redmart.com/fresh-produce/fresh-vegetables')
# Wait for the dynamically loaded elements to show up
WebDriverWait(wd, 300).until(
EC.visibility_of_element_located((By.CLASS_NAME, "productDescriptionAndPrice")))
# And grab the page HTML source
html_page = wd.page_source
wd.quit()
# Now you can use html_page as you like
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_page, 'lxml')
print(soup)
我需要使用 Selenium,因为页面是 JAVAscript 生成的,所以源代码没有用。如果您打开该页面,它有大约 60 行产品(总共大约 360 种产品)。运行此代码只会给我 6 行产品。停在黄洋葱上。
谢谢!
【问题讨论】:
-
把
WebDriverWait(wd, 300).until换成静态休眠很久。如果有效,则表示您的等待还不够。 -
当您向下滚动时,页面正在生成元素。向脚本添加滚动将加载更多项目。您可能需要等到加载所需数量的项目。
-
@JT 您的具体要求是什么?您是否要抓取所有 600 种产品?
-
感谢大家的回复。在这两者之间,我正在尝试一些事情。 @DebanjanB 是的,我正在尝试提取所有产品。我尝试了睡眠,但正如 KDM 提到的,当我向下滚动时,这些项目会加载。所以我想我必须在代码中添加一些滚动。我也做了手动滚动,所以在页面弹出的时候,我加了一个time.sleep(30),在这期间,我手动用鼠标滚动,直到600个产品全部显示出来,到了页面底部.然后代码接管了,但这次我只得到了 60 行中的最后 22 行产品....
标签: python selenium selenium-webdriver web-scraping webdriver