我想抓取一个 HTML 页面,其中内容不是静态的,而是用 javascript 加载的。
我将Selenium降级到版本
3.3.0
以便能够支持PhantomJS(v4.9.x
不再支持PhantomJS)并编写了以下代码:
from selenium import webdriver
driver = webdriver.PhantomJS('path-to-phantomJS')
driver.get('my_url')
p_element = driver.find_element_by_id(id_='my-id')
print(p_element)
我收到的错误是:
selenium.common.exceptions.NoSuchElementException: Message: "errorMessage":"Unable to find element with id 'my-id'"
我要返回的元素是带有某个
<section>
及其所有子标签的标签 id
。 HTML内容是这样的:
<section id="my-id" class="my-class">...</section>
这个错误信息...
selenium.common.exceptions.NoSuchElementException: Message: "errorMessage":"Unable to find element with id 'my-id'
...意味着在 HTML DOM 中找不到该元素。
可能的原因是所需的 WebElement 没有在 Viewport 中 render,因为 phantomjs 默认使用 最小化 视口进行初始化。
您需要使用最大化视口初始化PhantomJS,为visibility_of_element_ located()引入WebDriverWait,同时按如下方式定位它:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
driver = webdriver.PhantomJS('path-to-phantomJS')
driver.get('my_url')
driver.maximize_window()
p_element = WebDriverWait(driver, 20).until(EC.visibility_of_element_located((By.ID, "my-id")))
print(p_element)
这可能是由于各种原因造成的,例如执行代码时元素不存在或元素具有不同的 ID,但如果您仔细检查了 ID 是否存在。我认为在尝试查找元素之前,您必须确保页面已完成加载。在某些情况下,基于 JS 的内容可能需要更长的时间来加载。您可以添加延迟或显式的 wait 以确保该元素在访问之前可用
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException
driver = webdriver.PhantomJS('path-to-phantomJS')
driver.get('my_url')
delay = 10 # Wait up to 10 seconds for the element to be present
try:
wait = WebDriverWait(driver, delay)
p_element = wait.until(EC.presence_of_element_located((By.ID, 'my-id')))
print(p_element.text)
except TimeoutException:
print("Timeout!")
希望这有帮助!