我用 python 结合 selenium 编写了一个脚本,以从网页中的一些图像中获取一些标题。问题是我想要解析的内容位于该页面底部附近。所以,如果我尝试像传统的方式来获取它,浏览就会失败。
因此,我在抓取工具中使用了 JavaScript 代码,让浏览器滚动到底部并且它起作用了。
但是,我认为这不是一个很好的解决方案,可以尝试使用 .scrollIntoView()
但也不起作用。实现这一目的的理想方式是什么?
这是我的脚本:
from selenium import webdriver
import time
URL = "https://www.99acres.com/supertech-cape-town-sector-74-noida-npxid-r922?sid=UiB8IFFTIHwgUyB8IzMxIyAgfCAxIHwgNyM0MyMgfCA4MjEyIHwjNSMgIHwg"
driver = webdriver.Chrome()
driver.get(URL)
driver.execute_script("window.scrollTo(0, document.body.scrollHeight);") #I don't wish to keep this line
time.sleep(3)
for item in driver.find_elements_by_css_selector("#carousel img"):
print(item.get_attribute("title"))
driver.quit()
最佳答案
尝试使用下面的代码,它应该允许您滚动到所需的节点并抓取图像:
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
banks = driver.find_element_by_id("xidBankSection")
driver.execute_script("arguments[0].scrollIntoView();", banks)
images = WebDriverWait(driver, 5).until(EC.presence_of_all_elements_located((By.CSS_SELECTOR, "#carousel img")))
for image in images:
print(image.get_attribute("title"))
一些解释:最初这些图像在源代码中不存在,并且一旦滚动到 BankSection 就会在 BankSection 中生成,因此您需要向下滚动到 BankSection 并等待图像生成
关于python - 无法以正确的方式从网页收集标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48499652/