Python 网页抓取结果低于预期

时间:2021-05-18 02:18:14

标签: python html selenium

我尝试使用 Selenium 抓取网络数据,在浏览器上单击加载更多按钮几次后,它加载了所有 346 个产品,但是,它只显示 96 / 346 产品而不是 346 / 346 产品,任何想法如何解决它?我已经将抓取代码放在 while true 循环之后,用于单击加载更多按钮

screen capture of the result


from urllib.request import urlopen
import requests
import ast
from selenium import webdriver
driver=webdriver.Chrome('e:/Users/fungc1/Documents/chromedriver.exe')
from selenium.webdriver.chrome.options import Options
import time
from selenium.webdriver.common.action_chains import ActionChains
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.webdriver.common.action_chains import ActionChains
options=Options()

from bs4 import BeautifulSoup

url="https://www.toysrus.com.sg/lego"


#data = soup.findAll('div',attrs={'class':'card-image-wrapper'})
#toc = soup.find_all('div',attrs={'class':'result-count text-center'})
driver.get(url)
driver.maximize_window()
time.sleep(5)
driver.find_element_by_link_text("STAY ON THE SINGAPORE SITE").click() 

while True:
    try:
                                      
        driver.execute_script("var scrollingElement = (document.scrollingElement || document.body);scrollingElement.scrollTop = scrollingElement.scrollHeight;")
        wait=WebDriverWait(driver, 10)
        wait.until(EC.element_to_be_clickable((By.CSS_SELECTOR, "button.btn[data-url*='www.toysrus.com']"))).click()
        time.sleep(5)
    except Exception as e:
        print(e)
        break
        time.sleep(5)
        
        
response = requests.get(url)
response_text = response.text
soup = BeautifulSoup(response_text, 'lxml')
text = urlopen(url).read()
soup = BeautifulSoup(text)

data = soup.findAll('div',attrs={'class':'card-image-wrapper'})
toc = soup.find_all('div',attrs={'class':'result-count text-center'})




emptylist2=[]
for item in toc:
    print((item).text.strip()[:-1])
    
    for div in data:
        links = div.findAll('a')
        for a in links:
            catalogueresult=ast.literal_eval("" + a['href'][1:-5][-7:])
        emptylist2.append(catalogueresult)
    print (emptylist2)










1 个答案:

答案 0 :(得分:0)

你混合了一些东西。 您使用 Selenium 打开浏览器并通过单击加载按钮加载所有项目。但是在那之后,您使用请求库再次从与 Selenium 无关的 url 请求新的 html。所以,你正在做两件不同的事情。在您的情况下,即使您删除了 Selenium 代码,您也会得到同样的结果,因为您在加载所有产品后并未使用 Selenium。

现在,您需要做的是让Selenium返回所有396个产品的html代码,以便您将其交给BeautifulSoup进行进一步解析。

要做到这一点,您不需要在 while 循环结束后的前 4 行。做这样的事情:

html = driver.page_source #will return the html code with all products
soup = BeautifulSoup(html, 'lxml')

有了这个,您将获得所有 396 种产品。

相关问题