首页 > 解决方案 > 使用 selenium 进行网页抓取,但无法转到下一个网页

问题描述

所以我一直在尝试从ZALORA 网络抓取,似乎 selenium 一直在抓取重复的数据......

这是我的代码:

from selenium import webdriver
import time

driver = webdriver.Chrome()
url = 'https://www.zalora.com.hk/men/clothing/shirt/?gender=men&dir=desc&sort=popularity&category_id=31&page=1&enable_visual_sort=1'
driver.get(url)
driver.implicitly_wait(30)

brandname=''
productTitle=''
page=0

while True:
    info_brandname = ''
    info_product_title = ''
    page=page+1

    if len(info_brandname) < 99 or len(info_product_title) < 99:
        info_brandname = driver.find_elements_by_xpath('//span[@class="b-catalogList__itmBrand fsm txtDark uc js-catalogProductTitle"]')
        info_product_title = driver.find_elements_by_xpath('//em[@class="b-catalogList__itmTitle fss"]')
        print('info_brandname ' + str(len(info_brandname)) + ' at page ' + str(page))
        print('info_product_title ' + str(len(info_product_title)) + ' at page ' + str(page))

    else:
        print('info_brandname ' + str(len(info_brandname)) + ' at page ' + str(page))
        print('info_product_title ' + str(len(info_product_title)) + ' at page ' + str(page))

    #some manipulation of the scrapped data
    for i in range(len(info_brandname)):
        brandname = brandname + '\n' + info_brandname[i].text
        productTitle = productTitle + '\n' + info_product_title[i].text

    print(brandname.split('\n')[1:])
    print(productTitle.split('\n')[1:])

这是我怀疑出错的部分:

    #go to the next page before it loops again
    try:
        test = driver.find_element_by_xpath("//a[@title='Next']")
        driver.execute_script("arguments[0].click();", test)
    except:
        print('there is no next page man...')

    time.sleep(2)
    print(str(driver.current_url))

driver.close()

编辑:目前,根据网站,最后一个项目的名称应该是“Life8”,但我得到了“J.Crew”,我总共刮了 1885 个项目,而网站说他们总共只有 1847 个项目.
页面的 url 在脚本运行时实际上正在发生变化,以及每个页面上的项目,当我看到自动化在 chrome 上执行它的操作时,一切都正常运行,只是 selenium 抓取的数据很奇怪。

EDIT2:我做了更多调查,我在webdrive Chrome中监控了自动化过程,发现当我在普通Chrome中正常浏览ZALORA时,webdrive Chrome中的同一个url与同一个url的内容不同,是否有可能该网站做了什么来防止人们刮擦?

标签: pythonseleniumbeautifulsoup

解决方案


我认为问题在于您试图在单击“下一步”按钮后立即获取新 URL,而 URL 需要一些时间来更改,因此每次导航到同一页面时。

实际上我不知道为什么你需要driver.get(url)在每次迭代开始时通过单击下一步切换到下一页...

尝试仅删除此行driver.get(url)(将其移出循环),然后url = driver.current_url

另请注意,您只能driver.implicitly_wait(30)在脚本中调用一次(您可以将其放在 之后driver = webdriver.Chrome()),它将应用于所有元素搜索...


推荐阅读