python - 第 2 页上的下一个按钮 XPath 更改,不会循环
问题描述
我有一个脚本循环遍历标题的一系列元素,然后单击“下一步”以加载下一系列要抓取的元素。问题是第 2 页和很可能在第 3 页上的“下一步”按钮更改的 xpath。我不能使用按类查找或按 ID 查找,因为这些类/ID 名称不止一次出现。一旦在第二页找不到“下一步”按钮,脚本就会出错。
while True:
deal_title = browser.find_elements_by_xpath("//a[@id='dealTitle']/span")
titles = []
for title in deal_title:
titles.append(title.text)
deal_link = browser.find_elements_by_xpath("//div[@class='a-row dealDetailContainer']/div/a[@id='dealTitle']")
links = []
for link in deal_link:
links.append(link.get_attribute('href'))
deal_image = browser.find_elements_by_xpath("//a[@id='dealImage']/div/div/div/img")
images = []
for image in deal_image:
images.append(image.get_attribute('src'))
deal_price = browser.find_elements_by_xpath("//div[@class='a-row priceBlock unitLineHeight']/span")
prices = []
for price in deal_price:
prices.append(price.text)
try:
#clicks next button - this is the xpath for the page 1 button
browser.find_element_by_xpath("//span[@class='a-declarative']/div[2]/ul/li[@class='a-last']/a").click()
except NoSuchElementException:
break
下面是第 2 页上下一步按钮的 xpath:
browser.find_element_by_xpath("//span[@class='a-declarative']/div[1]/ul/li[@class='a-last']/a").click()
解决方案
您可以将它们结合在一起 browser.find_element_by_xpath("//span[@class='a-declarative']/div[2]/ul/li[@class='a-last']/a|//span[@ class='a-declarative']/div[1]/ul/li[@class='a-last']/a ").click() 或者你可以写一个更通用的 xpath //li[@class= '最后一个']/a
推荐阅读
- node.js - Nodejs:在ejs renderFile函数中,链接的CSS文件在回调HTML中不起作用
- django - 无法连接到 amqp://guest:**@127.0.0.1:5672//:
- python - python烧瓶应用JWT的理解
- onesignal - Onesignal 不提供所有通知
- python - 如何在python的一列中插入2个图
- javascript - 如何获取可滚动弹出窗口的scrollY位置
- python-3.x - 代码逐帧执行,但不是 MediaPipe 行一起执行
- sql - 在 google bigquery 中编辑“视图”
- c# - 无法更改 TextBox 文本
- qt - 选择时 QScintilla 自定义词法分析器额外空间