Selenium Python - 访问搜索结果的下一页

时间:2014-06-11 15:20:31

标签: python selenium web-scraping

我必须从此网址逐个点击每个搜索结果:

Search Guidelines

我首先从显示的文本中提取结果总数,以便我可以设置迭代的上限

upperlimit=driver.find_element_by_id("total_results")
number = int(upperlimit.text.split(' ')[0])

然后该循环被定义为 for i in range(1,number):

但是,在完成第一页上的前10个结果后,列表索引超出范围(可能是因为没有更多链接点击)。我需要点击"下一步"得到接下来的10个结果,依此类推,直到我完成所有搜索结果。我该怎么做呢?

任何帮助将不胜感激!

2 个答案:

答案 0 :(得分:1)

问题是,在加载页面后,标识为total_results的元素的值会发生变化,首先它包含117,然后更改为44

相反,这是一种更强大的方法。它逐页处理,直到没有剩余页面为止:

from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException

driver = webdriver.Firefox()
url = 'http://www.nice.org.uk/Search.do?searchText=bevacizumab&newsearch=true#/search/?searchText=bevacizumab&mode=&staticTitle=false&SEARCHTYPE_all2=true&SEARCHTYPE_all1=&SEARCHTYPE=GUIDANCE&TOPICLVL0_all2=true&TOPICLVL0_all1=&HIDEFILTER=TOPICLVL1&HIDEFILTER=TOPICLVL2&TREATMENTS_all2=true&TREATMENTS_all1=&GUIDANCETYPE_all2=true&GUIDANCETYPE_all1=&STATUS_all2=true&STATUS_all1=&HIDEFILTER=EGAPREFERENCE&HIDEFILTER=TOPICLVL3&DATEFILTER_ALL=ALL&DATEFILTER_PREV=ALL&custom_date_from=&custom_date_to=11-06-2014&PAGINATIONURL=%2FSearch.do%3FsearchText%40%40bevacizumab%26newsearch%40%40true%26page%40%40&SORTORDER=BESTMATCH'
driver.get(url)

page_number = 1
while True:
    try:
        link = driver.find_element_by_link_text(str(page_number))
    except NoSuchElementException:
        break
    link.click()
    print driver.current_url
    page_number += 1

基本上,这里的想法是获取下一页链接,直到没有这样的链接(NoSuchElementException将被抛出)。请注意,它适用于任意数量的页面和结果。

打印:

http://www.nice.org.uk/Search.do?searchText=bevacizumab&newsearch=true&page=1
http://www.nice.org.uk/Search.do?searchText=bevacizumab&newsearch=true&page=2#showfilter
http://www.nice.org.uk/Search.do?searchText=bevacizumab&newsearch=true&page=3#showfilter
http://www.nice.org.uk/Search.do?searchText=bevacizumab&newsearch=true&page=4#showfilter
http://www.nice.org.uk/Search.do?searchText=bevacizumab&newsearch=true&page=5#showfilter

答案 1 :(得分:0)

甚至没有必要以编程方式按下Next按钮,如果你看得很清楚,那么在浏览其他结果页面时,网址只需要一个新参数:

url = "http://www.nice.org.uk/Search.do?searchText=bevacizumab&newsearch=true&page={}#showfilter"

for i in range(1,5):
    driver.get(url.format(i))

    upperlimit=driver.find_element_by_id("total_results")
    number = int(upperlimit.text.split(' ')[0])

如果你仍然想以编程方式按下你可以使用的下一个按钮:

driver.find_element_by_class_name('next').click()

但我没有测试过。