我正在尝试使用“硒”构建一个爬虫。 我该如何处理分页部分?
以下类适用于html页面中的下一个和上一个按钮:
下一个按钮的类别为下一个回顾, 上一个按钮的类别是preview-prev。
如果分页到达末尾, (当没有review-next类是下一个按钮类时) 我想返回并继续进行爬网。 (我尝试从停下的地方返回,而不是从第一个开始)
相反,如果没有以前按钮类的review-prev类,它将再次前进。
换句话说,您想让分页重复运行。
到目前为止,以下是我的代码。
*说明其他问题。
首先, 如果当前页面上没有下一个按钮(下一个类复习) 我想返回上一页并开始爬网。
即使上一页上有一个下一个按钮(下一个类复习) 从那时起,我们将尝试向后爬网。
总结一下, 如果没有下一个按钮(下一个类复习) 当我们返回时,即使有一个下一个按钮(class review-next),我们也会返回。
<table>
<tbody>
<tr>
<td class="num">512</td>
<td class="thumb"><img src="test.jpg"></td>
<td class="subject">
<a href="/article/band/13538" id="re_href" class="re_href">Title</a>
</td>
<td class="writer"></td>
<td class="check"></td>
</tr>
<tr>
<td class="num">512</td>
<td class="thumb"><img src="test2.jpg"></td>
<td class="subject">
<a href="/article/band/14230" id="re_href" class="re_href">Title</a>
</td>
<td class="writer"></td>
<td class="check"></td>
</tr>
.
.
.
</tbody>
</table>
<div class="base-paginate">
<a href="?page=2" class="review-prev" title="prev-page"><img src="/btn_page_prev.gif" alt="prev-page"></a>
<ol>
<li><a href=""></a></li>
<li><a href=""></a></li>
<li><a href=""></a></li>
</ol>
<a href="?page=3" class="review-next" title="next-page"><img src="/btn_page_next.gif" alt="next-page"></a>
</div>
from time import sleep
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
driver = webdriver.Chrome()
driver.set_page_load_timeout(60)
def close():
driver.get('/test&page=1')
def start():
driver.get('/test&page=1')
sleep(2)
list_of_links = []
while True:
list_of_links = driver.find_elements_by_xpath("//table//tr//td[@class='subject left txtBreak']/a")
sleep(2)
for linktext in range(len(list_of_links)):
list_of_links = driver.find_elements_by_xpath("//table//tr//td[@class='subject left txtBreak']/a")
element = list_of_links[linktext]
driver.execute_script("arguments[0].click();", element)
sleep(3)
driver.back()
sleep(3)
try:
driver.find_element_by_xpath("//a[@class='review-next']").click()
except NoSuchElementException :
break
list_of_links = set(list_of_links)
driver.close()
return list_of_links
if __name__ == '__main__':
list_of_links = start()
答案 0 :(得分:1)
如果我对您的理解是正确的,那么您在碰壁时会尝试返回两页,因此这样的东西(或已编辑的东西)应该可以工作
type_of-button = "//a[@class='review-next']"
while True:
previous_url = driver.current_url
list_of_links = driver.find_elements_by_xpath("//table//tr//td[@class='subject left txtBreak']/a")
sleep(2)
for linktext in range(len(list_of_links)):
list_of_links = driver.find_elements_by_xpath("//table//tr//td[@class='subject left txtBreak']/a")
element = list_of_links[linktext]
driver.execute_script("arguments[0].click();", element)
sleep(3)
driver.back()
sleep(3)
try:
driver.find_element_by_xpath(type_of_button).click()
except NoSuchElementException :
driver.get(previous_url)
type_of_button = "//a[@class='review-prev']"
list_of_links = set(list_of_links)
driver.close()
return list_of_links
也请尽量不要使用睡眠。阅读
并实施它,方法sleep会创建很多错误。
现在,也没有刹车点,因此您需要添加一些刹车点以避免无限循环