python - 无法以正确的方式从网页收集标题

标签 python python-3.x selenium selenium-webdriver web-scraping

我用 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/

相关文章:

java - Selenium:启动 IE 时出现意外错误。浏览器缩放级别设置为 122%。应设置为 100%

java - 如何在 selenium webdriver 中验证标题

testing - 从动态生成的列表框中选择日期值

python - 在 windows 10 中安装 postgresql

python-3.x - 如何生成频率为周二至周六(含)的 Pandas 日期范围?

python - 从另一个对象分配 __len__() 方法

python - 将 .csv 数据重写到文件会在 python 中创建人工第一列

python - 使用 Tkinter 在 Python 中进行内存游戏

Python:从命令输出中读取

python - 将包含多行字符串的 Pandas 系列行拆分为单独的行