python - Selenium PhantomJS webdriver 无法获取 ajax 内容

标签 python ajax selenium selenium-webdriver phantomjs

我正在尝试抓取一个通过 ajax 加载大部分内容的页面。

我正在尝试从 this webpage 中获取所有具有 data-section 属性的 li 节点| , 例如。响应 html 有六个我需要的必需节点,但其余大部分是通过 ajax 请求加载的,该请求返回包含剩余 li 节点的 html。

所以我从使用请求切换到使用 selenium 和 PhantomJS 驱动程序,它应该是 xhr 友好的,但我没有得到额外的 ajax 加载内容。

可运行:

from selenium import webdriver
from lxml import html

br = webdriver.PhantomJS()
br.get(url)
tree = html.fromstring(br.page_source)
print tree.xpath('//li[@data-section]/a/text()')

简而言之,上面的代码无法通过xhr将html注入(inject)到网页中。我怎样才能让它这样做?如果没有,我的其他 headless 选项是什么。

最佳答案

链接页面显眼地显示一个加载微调器 (.archive_loading_bar),它会在数据加载后立即消失。您可以使用 explicit wait具有 invisibility_of_element_located 的预期条件。

from selenium.webdriver.common.by import By
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium import webdriver
from lxml import html

driver = webdriver.PhantomJS()
driver.get(url)
wait = WebDriverWait(driver, 10)
wait.until(EC.invisibility_of_element_located((By.CSS_SELECTOR, '.archive_loading_bar')))
tree = html.fromstring(driver.page_source)

本文改编自this answer并最多等待 10 秒或直到数据加载完毕。

关于python - Selenium PhantomJS webdriver 无法获取 ajax 内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26948584/

相关文章:

class - WebDriver 页面对象和大量定位器

python - 如何在 Python 中正确定义静态实用程序类

python - 在mod_python下执行模块时出现ImportError

javascript - 如何在 flask 中使用 ajax 从 sql 调用用户名?

java - 检查对象是否存在被 webdrivereventlistener 捕获时,Selenium webdriver 出错?

python - 用 selenium python 驱动 Opera

python - 键入库中的示例代码导致 TypeError : 'type' object is not subscriptable, 为什么?

python - 从函数中获取对应的模块

javascript - 当从另一台计算机或手机添加数据时,如何更新计算机上的 View ?

jquery - 将 XMLHttpRequest 转换为 jquery