python - 问题爬取亚马逊,元素无法滚动到 View 中

标签 python selenium web-scraping web-crawler screen-scraping

我在 Amazon 上抓取页面时遇到问题。

我试过使用:

  • 执行 JS 脚本
  • 行动链
  • 显式等待

似乎没有任何效果。一切都会抛出一个异常或错误。

基本脚本

ff = create_webdriver_instance()
ff.get('https://www.amazon.ca/gp/goldbox/ref=gbps_ftr_s-3_4bc8_dct_10-?gb_f_c2xvdC0z=sortOrder:BY_SCORE,discountRanges:10-25%252C25-50%252C50-70%252C70-&pf_rd_p=f5836aee-0969-4c39-9720-4f0cacf64bc8&pf_rd_s=slot-3&pf_rd_t=701&pf_rd_i=gb_main&pf_rd_m=A3DWYIK6Y9EEQB&pf_rd_r=CQ7KBNXT36G95190QJB1&ie=UTF8')
next_button = ff.find_element_by_xpath('(//li/a[contains(text(), "Next")])[1]')

尝试 #1:执行 JS

脚本

ff.execute_script('arguments[0].scrollIntoView()', next_button)

错误

元素无法滚动到 View 中

尝试 #2: Action 链

脚本

actions = ActionChains(ff)
actions.move_to_element(next_button)
actions.click(next_button)
actions.perform()

错误

TypeError: rect 未定义

尝试 #3:显式等待

next_button = WebDriverWait(ff, 60).until(
    EC.visibility_of_element_located((By.XPATH, '(//li/a[contains(text(), "Next")])[1]'))
)

我也尝试过使用 element_to_be_clickable。这两个最终都会超时。

最佳答案

那是因为您正在尝试处理隐藏链接。试试下面的方法

next_button = ff.find_element_by_partial_link_text('Next')
next_button.click()

next _button = ff.find_element_by_link_text('Next→')

请注意,find_element_by_partial_link_text/find_element_by_link_text 仅搜索可见 链接。

你可能还需要打电话

ff.implicitly_wait(10)

一旦在你的脚本中(在你的 WebDriver 实例定义之后的某个地方)或使用如下的 ExplicitWait

from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

next_button = WebDriverWait(ff, 10).until(EC.element_to_be_clickable((By.LINK_TEXT, 'Next→')))

确保即使有渲染延迟也能找到所需的元素

关于python - 问题爬取亚马逊,元素无法滚动到 View 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52356838/

相关文章:

python - 关闭的文件描述符是怎么回事?

Selenium/hub 在 network_mode = "host"时无法识别 selenium/node-chrome-debug

python - CrawlSpider 派生对象 das 没有属性 'state'

python - HTTP 错误 403 : Forbidden with exception handling

python - Json,抓取到网页 - python

python - 使用 QTextCharFormat 更改选择颜色

python - pandas 在 DatetimeIndex 转换时引发 ValueError

java - 如何在 Selenium 的 Xpath 中转义双引号?

python - 在 Linux 上使用 headless Chrome 访问拒绝页面,而有头 Chrome 通过 Python 使用 Selenium 在 Windows 上运行

python - 从 Pandas 数据框中提取单个值