python - 使用 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的内容不同,是否有可能该网站做了什么来防止人们刮擦?
解决方案
我认为问题在于您试图在单击“下一步”按钮后立即获取新 URL,而 URL 需要一些时间来更改,因此每次导航到同一页面时。
实际上我不知道为什么你需要driver.get(url)
在每次迭代开始时通过单击下一步切换到下一页...
尝试仅删除此行driver.get(url)
(将其移出循环),然后url = driver.current_url
另请注意,您只能driver.implicitly_wait(30)
在脚本中调用一次(您可以将其放在 之后driver = webdriver.Chrome()
),它将应用于所有元素搜索...
推荐阅读
- php - Laravel 使用 GroupBy 显示日期/计数
- xml - 将属性中的分隔行转换为 ant 中的逗号分隔字符串
- java - 安全存储用户邮箱的密码
- c - Polyspace 发出关于系统函数使用系统定义参数标志的警报
- javascript - 一个按钮可在单击时执行三个或更多操作
- sql - 试图创建一个触发器让用户一天只插入 5 次
- mysql - MySql 事件调度器每天在特定时间复制和插入
- asp.net-core - Kestrel 服务器错误 - 应用程序在未读取整个请求正文的情况下完成
- r - 条形图标签下标不使用表达式
- ruby - 核心 2.3.0 与 stdlib 2.5.3 的时间