【问题标题】:Python web crawling result is less than expectedPython网络爬取结果不及预期
【发布时间】:2021-05-18 11:06:00
【问题描述】:

我尝试使用 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)










【问题讨论】:

    标签: python html selenium


    【解决方案1】:

    你混合了一些东西。 您使用 Selenium 打开浏览器并通过单击加载按钮加载所有项目。但在那之后,您使用 requests 库再次从与 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 种产品。

    【讨论】:

    • 我投了你一票,但上面写着:感谢您的反馈!您需要至少 15 声望才能投票,但您的反馈已被记录。
    猜你喜欢
    • 1970-01-01
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 2010-10-28
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多