Python 在页面上循环,直到它能够';找不到下一个链接
我有一个函数“find_products()”,它在页面上的产品上循环并打印型号。那很好。在它从页面上刮下产品后,我希望它单击下一步按钮(如果存在)。为了测试XPath,我使用“try”来确保元素存在。这是可行的,但当然,它不会循环。我正在努力将其转换为循环,并不断调用单击“下一页”并调用product函数,直到XPath不返回下一页链接Python 在页面上循环,直到它能够';找不到下一个链接,python,loops,Python,Loops,我有一个函数“find_products()”,它在页面上的产品上循环并打印型号。那很好。在它从页面上刮下产品后,我希望它单击下一步按钮(如果存在)。为了测试XPath,我使用“try”来确保元素存在。这是可行的,但当然,它不会循环。我正在努力将其转换为循环,并不断调用单击“下一页”并调用product函数,直到XPath不返回下一页链接 try: nextpage=driver.find_element_by_xpath('//span[@class="srSprite pagnNextAr
try:
nextpage=driver.find_element_by_xpath('//span[@class="srSprite pagnNextArrow"]')
except:
find_products() # calls function with loop to extract products
print("Didnt Find Next Page")
time.sleep(10)
driver.close()
else:
find_products()
nextpage.click()
print("i just clicked next page")
time.sleep(10)
就像另一个用户批准的答案一样,下面这段代码似乎很有效。我需要一些帮助的是,是什么让下面的代码示例中的“try”为false?当find\u元素\u by\u xpath不返回任何内容时,“try”是否失败并变为false?这比公认的答案好还是坏
while True:
try:
nextpage=driver.find_element_by_xpath('//span[@class="srSprite pagnNextArrow"]')
find_products()
print("clicking next page")
nextpage.click()
time.sleep(5)
except:
break
find_products() #pick up the products on the last page.
您可以使用
while
循环和bool
变量检查刮板何时找到下一个元素。你可以这样修改你的代码
found = True
while(found):
try:
nextpage=driver.find_element_by_xpath('//span[@class="srSprite pagnNextArrow"]')
except:
find_products() # calls function with loop to extract products
print("Didnt Find Next Page")
time.sleep(10)
driver.close()
found = False
else:
find_products()
nextpage.click()
print("i just clicked next page")
time.sleep(10)
为了使您仅在代码找不到下一页时终止,您应按如下方式重新构造代码:
def nextPage():
is_next_page_found = True
while is_next_page_found:
try:
nextpage=driver.find_element_by_xpath('//span[@class="srSprite pagnNextArrow"]')
except:
# this will terminate the while loop
is_next_page_found = False
else:
find_products()
nextpage.click()
time.sleep(10)
# after breaking out of the loop
driver.close()
你试过把它放在
while
循环中吗?我想这是我需要的,但对while循环以及它如何通过xpatch与find\u元素交互感到困惑。下面是我的另一段代码,我不确定什么时候符合真值。是在try的第一行时(可以找到正则表达式),还是直到出现错误时才为真,而true:try:ViewMore=driver.find_element_by_xpath('//a[@id=“list-view\u load-more--js”]')ViewMore.click()打印(“单击更多”)时间。睡眠(2)除了:break我认为第二个代码块是另一个问题,因此你应该为该部分提出一个新的问题。这是可行的。。下面我还有另一个解决方案,似乎很有效,但我不明白是什么让“尝试”失败了。