您的位置:首页技术文章
文章详情页

crawler - 如何在 Python 爬虫中完成 JavaScript 函数翻页?

浏览:54日期:2022-06-28 16:18:43

问题描述

本人爬取一个网页时注意到它的翻页时靠这样的一个函数实现的, 翻页之后页面网址也不变:

<input name='goto2' onclick='dirGroupMblogToPage(document.getElementById(’dirGroupMblogcp2’).value)' type='button' value='Go'/> </input> function dirGroupMblogToPage(currentPage){ jQuery.post('dirGroupMblog.action', {'page.currentPage':currentPage,gid:MI.TalkBox.gid}, function(data){$('#talkMain').html(data);window.scrollTo(0, $css.getY(MI.talkList._body)-65); });}

crawler - 如何在 Python 爬虫中完成 JavaScript 函数翻页?

写了这样的函数试图实现翻页:

def login_page(login_url, content_url, usr_name='******@126.com', passwd='******'): # 实现登录, 返回Session对象和获得的页面 post_data = {’r’: ’on’, ’u’: usr_name, ’p’: passwd} s = requests.Session() s.post(login_url, post_data) r = s.get(content_url) return s, rdef turn_page(s, next_page, content_url): post_url = 'http://sns.icourses.cn/dirGroupMblog.action' post_headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36','X-Requested-With':'XMLHttpRequest'} post_data = {'page.currentPage': next_page, 'gid': 2632} s.post(post_url, data=post_data, headers = post_headers) res = s.get(content_url) return res

但是调用turn_page()之后没能实现翻页。请问应该怎么解决这个问题? 另外请问想要解决好这类问题需要自学哪些方面的知识呢?谢谢!

问题解答

回答1:

推荐使用 selenium

例如,如果需要点击界面上,下一页的按钮,或者说需要输入上下左右键,页面可以翻页,selenium webdriver可以做到,给出一个参考(我以前用来爬起点中文网的小说)

selenium 可以与页面进行交互,单击,双击,输入,等待页面加载(隐式等待,和显式等待)。。。。

from selenium import webdriver# from selenium.webdriver.common.keys import Keys#driver = webdriver.PhantomJS(executable_path='D:phantomjs-2.1.1-windowsbinphantomjs')# 我的windows 已配置环境变量,不需指定 executable_path,使用 Chrome需要对应的浏览器以及驱动程序driver = webdriver.Chrome()# url 为你需要加载的页面urlurl = ’http://sns.icourses.cn/*****’# 打开页面driver.get(url)# 在你的例子中,是需要点击 button ,通过class 属性获取到button,然后执行单击 .click()# 如果需要准确定位,可以自行搜索其他的 find_driver.find_element_by_class_name('buttonJump').click()# selenium webdriver 还有很多其它高级的用法,自行谷歌,你这个问题,搜索应该是能得到答案的,回答2:

分几种情况,1、页面上通过 js 效果实现滑动或者点击实现翻页;2、页面上通过超链接点击实现翻页;

可以通过 chrome 的开发者工具中的 network 分析得到结果反会的是 html 页面还是反馈 json 渲染。json 的话就好办了,直接拿结果。普通html 页面需要使用正则匹配到换页。然后将链接放入待爬的池子中。

/a/11...

标签: Python 编程
相关文章: