首页 > 解决方案 > Trying to obtain the title of a website that is generated through javascript

问题描述

When I load up a website, its title is "Loading..." for a second, until it changes to a different title obtained through javascript. In python, I'm trying to obtain the generated title.

I've tried using selenium and PhantomJS, but I run into a number of problems.

from selenium import webdriver
driver = webdriver.PhantomJS(executable_path='/usr/local/lib/phantoms/bin/phantomjs')
driver.get(www.google.com)
p_element = driver.find_element_by_id(id='intro-text')
print(p_element.text)

That says that the support for PhantomJS has been deprecated, so I'm not sure what else to do, or if there's an easier method to obtain the result I need.

标签: pythonselenium

解决方案


使用 Firefox 或 Chrome 之类的东西,然后使用驱动程序的 title 属性

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.google.com")
print(driver.title)

如果标题短暂显示“正在加载...”,那么您可以循环获取标题,直到它不再显示“正在加载...”

from selenium import webdriver
driver = webdriver.Firefox()
driver.get("https://www.google.com")
while driver.title == 'Loading...':  //Should loop here until title changes
     pass
print(driver.title)

我的蟒蛇生锈了,但这应该很接近。


推荐阅读