如何通过Selenium / Python获取JavaScript编写的html内容[复制]
发布时间:2020-12-20 11:26:48 所属栏目:Python 来源:网络整理
导读:参见英文答案 Get HTML Source of WebElement in Selenium WebDriver using Python????????????????????????????????????13个 我正在使用Selenium进行网络爬行,我希望在Selenium模拟点击虚假链接后获得由JavaScript编写的元素(例如链接). 我尝试了get_html_s
参见英文答案 >
Get HTML Source of WebElement in Selenium WebDriver using Python????????????????????????????????????13个
我正在使用Selenium进行网络爬行,我希望在Selenium模拟点击虚假链接后获得由JavaScript编写的元素(例如链接). 我尝试了get_html_source(),但它不包含JavaScript编写的内容. 我编写的代码: def test_comment_url_fetch(self): sel = self.selenium sel.open("/rmrb") url = sel.get_location() #print url if url.startswith('http://login'): sel.open("/rmrb") i = 1 while True: try: if i == 1: sel.click("//div[@class='WB_feed_type SW_fun S_line2']/div/div/div[3]/div/a[4]") print "click" else: XPath = "//div[@class='WB_feed_type SW_fun S_line2'][%d]/div/div/div[3]/div/a[4]"%i sel.click(XPath) print "click" except Exception,e: print e break i += 1 html = sel.get_html_source() html_file = open("tmpfoo.html",'w') html_file.write(html.encode('utf-8')) html_file.close() 我使用while循环来点击一系列虚假链接,触发js-actions来显示额外的内容,而这些内容就是我想要的.但是sel.get_html_source()没有给出我想要的东西. 有人可以帮忙吗?非常感谢. 解决方法
由于我通常对获取的节点进行后处理,因此我使用execute_script直接在浏览器中运行JavaScript.例如,获取所有a-tags:
js_code = "return document.getElementsByTagName('a')" your_elements = sel.execute_script(js_code) 编辑:execute_script和get_eval是等效的,除了get_eval执行隐式返回,在execute_script中必须明确说明. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |