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

标签 python selenium web-scraping

我必须从这个网址一一点击每个搜索结果:

Search Guidelines

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

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

循环被定义为 对于范围内的 i(1,数字):

但是,在浏览完第一页上的前 10 个结果后,列表索引超出范围(可能是因为没有更多链接可供单击)。我需要单击“下一步”才能获取接下来的 10 个结果,依此类推,直到完成所有搜索结果。我怎样才能做到这一点?

如有任何帮助,我们将不胜感激!

最佳答案

问题在于 id 为 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

关于python - Selenium Python - 访问搜索结果的下一页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24166689/

相关文章:

python - 我可以异步执行 "apply"中的函数到 pandas 数据帧吗?

python - 带有字符数组的 Numpy ufunc.at

python - 如何在交互式绘图时摆脱最大递归深度错误?

python - 从 bash 脚本运行 "python manage.py runserver"

android - 如何将没有 API 和格式的网站抓取到移动应用程序(iPhone、Android 等)中?

python - 越来越大的正 WGAN-GP 损失

python - 如何关闭Selenium中的弹出窗口

javascript - executeScript - 注入(inject)提示和返回值 - 找不到值字段

python - 使用 BeautifulSoup 从上一页抓取

python - 在网页抓取时,当尝试计算页面上的项目数量时,即使有超过 1 个项目,我也会得到 1