python - 网页抓取 Shopee(导入图片网址)
问题描述
我正在尝试抓取 Shopee 的产品名称、价格和图片。但是,我似乎无法提取图像。是不是因为html?我似乎无法在 dataImg 中找到图像类
import pandas as pd
from selenium import webdriver
from bs4 import BeautifulSoup
driver =webdriver.Chrome('chromedriver')
products=[]
prices=[]
images=[]
driver.get('https://shopee.co.id/search?keyword=laptop')
content=driver.page_source
soup=BeautifulSoup(content)
soup
for link in soup.find_all('div',class_="_3EfFTx"):
print('test')
print(link)
for link in soup.find_all('div',class_="_3EfFTx"):
#print(link)
dataImg=link.find('img',class_="_1T9dHf V1Fpl5")
print(dataImg)
name=link.find('div',class_="_1Sxpvs")
#print(name.get_text())
price=link.find('div',class_="QmqjGn")
#print(price.get_text())
if dataImg is not None:
products.append(name.get_text())
prices.append(price.get_text())
images.append(dataImg['src'])
df=pd.DataFrame({'Product Name':products,'Price':prices,'Images':images})
df
解决方案
该网站使用 JS 加载图像,为了绕过这个,你需要 selenium 并有一个小的延迟。这是下载图像src的代码:
from selenium import webdriver
from time import sleep
products=[]
prices=[]
images=[]
driver = webdriver.Chrome(r'F:\Sonstiges\chromedriver\chromedriver.exe')
driver.get('https://shopee.co.id/search?keyword=laptop')
sleep(8)
imgs = driver.find_elements_by_class_name('_1T9dHf')
for img in imgs:
img_url = img.get_attribute("src")
if img_url:
print(img_url)
driver.quit()
为了获取图像,只需使用获取的 URI执行此操作。如果你使用 Beautiful soup 只是因为它在后台运行,那么这里是运行 selenium headless(在后台)的解决方案。
推荐阅读
- javascript - 我如何制作一个 booststraps 行 clickabel 并使用相同的行 id 打开一个模式
- rust - 如何制作一个可以在不使用“cargo run”的情况下执行的 Rust 程序?
- time - 离散时间序列预测:预测某些事物的时间和数量?
- python - 通过函数递增全局变量
- linux - 找不到使 g77 命令
- selenium - 我能够使用 xpath 找到元素。但是在执行脚本时它没有运行
- javascript - Mxgraph 如何以编程方式在形状内添加文本元素?
- python - 从数据框一列的所有行中删除 % 符号并将整个列值转换为浮点数
- image-processing - Cuda 内存分配
- java - 如何打印出 BFS 采用的路径?