gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:59:39 28 4
gpt4 key购买 nike

我正在尝试抓取一个通过 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com