使用selenium进行网页抓取,无法进入下一个网页

时间:2018-04-24 16:35:53

标签: python selenium beautifulsoup

所以我一直在尝试从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()

编辑:目前,最后一个项目的名称应为&#39; Life8&#39;根据网站的说法,我得到了J.Crew&#39;,我总共报废了1885件物品,而网站上说他们总共只有1847件物品。
页面&#39;当脚本运行时,url实际上正在改变,每个页面上的项目,当我看到自动化在chrome上执行其操作时,一切都正常运行,只有selenium报废的数据很奇怪。

EDIT2:我已经做了一些调查,我监控了webdrive Chrome中的自动化过程,并且发现当我在普通Chrome中正常浏览ZALORA时,webdrive Chrome中的相同网址与同一网址的内容不同,有可能该网站做了一些事情来防止人们报废?

2 个答案:

答案 0 :(得分:1)

我认为问题在于您在点击“下一步”按钮后尝试获取新的URL,而URL需要一些时间才能更改,因此每次导航到同一页面时都是如此。

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

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

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

答案 1 :(得分:0)

我设法通过将driver = webdriver.Chrome()更改为driver = webdriver.Firefox()来填充正确的数据,这解决了我遇到的问题。虽然我不完全确定为什么它解决了这些问题。

相关问题