如何使用Selenium / Python获取由JavaScript编写的html内容 - python

我正在使用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("tmp\\foo.html", 'w')
        html_file.write(html.encode('utf-8'))
        html_file.close()

我使用while循环单击一系列伪造的链接,这些伪造的链接触发js操作以显示额外的内容,而该内容正是我想要的。但是sel.get_html_source()没有提供我想要的东西。

有人可以帮忙吗?非常感谢。

参考方案

由于通常在获取的节点上进行后处理,因此我直接在浏览器中使用execute_script运行JavaScript。例如,获取所有a-tag:

js_code = "return document.getElementsByTagName('a')"
your_elements = sel.execute_script(js_code)

编辑:execute_scriptget_eval是等效的,除了get_eval执行隐式返回,在execute_script中必须明确声明。

如何使用Selenium Python注销linkedin - python

我正在尝试使用以下代码从linkedin注销,但它给了我这个错误:AttributeError:'list'对象没有属性'click'登录成功,但是不执行注销代码并退出。 from selenium import webdriver from selenium.webdriver.common.keys import Keys from selenium.w…

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

在返回'Response'(Python)中传递多个参数 - python

我在Angular工作,正在使用Http请求和响应。是否可以在“响应”中发送多个参数。角度文件:this.http.get("api/agent/applicationaware").subscribe((data:any)... python文件:def get(request): ... return Response(seriali…

Python exchangelib在子文件夹中读取邮件 - python

我想从Outlook邮箱的子文件夹中读取邮件。Inbox ├──myfolder 我可以使用account.inbox.all()阅读收件箱,但我想阅读myfolder中的邮件我尝试了此页面folder部分中的内容,但无法正确完成https://pypi.python.org/pypi/exchangelib/ 参考方案 您需要首先掌握Folder的myfo…

Python GPU资源利用 - python

我有一个Python脚本在某些深度学习模型上运行推理。有什么办法可以找出GPU资源的利用率水平?例如,使用着色器,float16乘法器等。我似乎在网上找不到太多有关这些GPU资源的文档。谢谢! 参考方案 您可以尝试在像Renderdoc这样的GPU分析器中运行pyxthon应用程序。它将分析您的跑步情况。您将能够获得有关已使用资源,已用缓冲区,不同渲染状态上…