如何处理JavaScript加载的图片?
时间: 2024-11-17 09:30:05 浏览: 19
处理JavaScript加载的图片通常需要通过浏览器自动化工具,如Selenium或者Puppeteer。这是因为直接发送HTTP请求可能无法获取到动态加载的内容。下面是一个使用Puppeteer的例子(Python版本通过`pupy`库间接调用):
```python
from playwright.async_api import async_playwright
async def scrape_js_images(url):
async with async_playwright() as p:
browser = await p.chromium.launch(headless=False) # 启动无头Chromium浏览器
page = await browser.new_page()
await page.goto(url)
# JavaScript渲染完成后,再查找图片
await page.wait_for_selector('img', timeout=10_000) # 等待图片加载
images = await page.locator('img').map(lambda x: x.src) # 获取所有图片链接
await browser.close()
return images
url_with_js = "http://example.com" # 替换为有JS加载图片的网页
js_images = await scrape_js_images(url_with_js)
```
在这个例子中,浏览器首先打开页面,然后等待所有图片加载完成,最后提取出图片的源URL。
阅读全文
相关推荐
















