Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/313.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中使用Selenium通过javascript添加内容来抓取网站_Javascript_Python_Selenium_Web Scraping_Phantomjs - Fatal编程技术网

在Python中使用Selenium通过javascript添加内容来抓取网站

在Python中使用Selenium通过javascript添加内容来抓取网站,javascript,python,selenium,web-scraping,phantomjs,Javascript,Python,Selenium,Web Scraping,Phantomjs,我正试图使用python中的Selenium和phantomjs从一个网站上抓取数据。然而,这个网站正在通过javascript添加我感兴趣的数据。有没有办法让Selnium在返回数据之前等待数据?到目前为止,我们已经尝试: import contextlib import selenium.webdriver as webdriver

我正试图使用python中的Selenium和phantomjs从一个网站上抓取数据。然而,这个网站正在通过javascript添加我感兴趣的数据。有没有办法让Selnium在返回数据之前等待数据?到目前为止,我们已经尝试:

import contextlib                                                                
import selenium.webdriver as webdriver                                           
import selenium.webdriver.support.ui as ui

phantomjs = '/usr/local/bin/phantomjs'                                           
url = '[redacted]'             

with contextlib.closing(webdriver.PhantomJS(phantomjs)) as driver:
    driver.get(url)
    wait = ui.WebDriverWait(driver, 10)
    wait.until(lambda driver: driver.execute_script("return document.getElementById(\"myID\").innerText").startswith('[redacted]'))
    driver.execute_script("return document.getElementById(\"myID\").innerText")
不幸的是,此代码引发了
selenium.common.exceptions.TimeoutException:Message:None
,因为我们获得的
id
的内容没有更改

我们在virtualenv和selenium 2.41.0中使用PhantomJS 1.9.7、python 2.7.5。这是正确的方法还是我们遗漏了什么。有没有人有更好的方法

提前谢谢

编辑

在@ExperimentsWithCode注释之后,我们尝试循环,直到加载内容:

with contextlib.closing(webdriver.PhantomJS(phantomjs)) as driver:
    driver.get(url)
    wait = ui.WebDriverWait(driver, 10)
    found = False
    while not found:
        try:
            wait.until(lambda driver: driver.execute_script("return document.getElementById(\"myID\").innerText").startswith('[redacted]'))
            driver.execute_script("return document.getElementById(\"myID\").innerText")
            found = True
        except:
             print "Not found"
             pass

假设在没有输入的情况下加载此内容,可以使用try语句执行循环。这样你就可以试着得到那个文本。如果未加载文本,它将重试,直到加载文本。使用编辑中的代码,文本似乎从未加载。一定有什么东西触发javascript或阻止它触发。你能描述一下你试图与之互动的元素吗。另外,当您运行此代码时,是否可以单击触发元素显示的内容,或者与之交互?如果try循环被注释掉了呢。在这种情况下,元素只是加载,还是由某些交互触发?还可以尝试两件事。我需要获取的元素只是div中的一些文本。当从常规浏览器访问时,该元素会根据控制台在一些请求后自动显示。如果
try
被注释掉,代码将抛出一个异常。有关于该请求的信息吗?此外,测试更多的是查看它是否在没有try语句的情况下出现。你犯了什么错误?是后来的代码吗?如果是这样的话,您是否可以注释掉代码的其余部分,以便浏览器挂起并查看元素是否出现。您是否尝试单击任何内容以查看是否启动了javascript?