BeautifulSoup找不到特定类别的div

时间:2019-04-21 22:41:45

标签: python html web-scraping beautifulsoup urllib3

Webpage HTML and my code

因此,在某些背景下,我一直在尝试学习网络抓取以获取涉及CNN的机器学习项目的某些图像。我一直在尝试从网站上抓取一些图像(左侧是HTML代码,右侧是我的代码);我的代码最终打印/返回一个空列表。我在做错什么吗?

出于价值考虑,我尝试查找其他具有'id'而不是'class'并且确实有效的div标签,但由于某种原因,它找不到我想要的标签。

编辑:

import requests
import urllib3
from bs4 import BeautifulSoup

http = urllib3.PoolManager()
url = 'https://www.grailed.com/shop/EkpEBRw4rw'

response = http.request('GET', url)
soup = BeautifulSoup(response.data, 'html.parser')

img_div = soup.findAll('div', {'class': "listing-cover-photo "})
print(img_div)

编辑2:

from bs4 import BeautifulSoup
from selenium import webdriver

url = 'https://www.grailed.com/shop/EkpEBRw4rw'
driver = webdriver.Chrome(executable_path='chromedriver.exe')
driver.get(url)
soup = BeautifulSoup(driver.page_source, 'html.parser')

listing = soup.select('.listing-cover-photo ')
for item in listing:
    print(item.select('img'))

输出:

[<img alt="Off-White Off White Caravaggio Hoodie" src="https://process.fs.grailed.com/AJdAgnqCST4iPtnUxiGtTz/cache=expiry:max/rotate=deg:exif/resize=width:480,height:640,fit:crop/output=format:webp,quality:70/compress/https://cdn.fs.grailed.com/api/file/yX8vvvBsTaugadX0jssT"/>]
(...a few more of these...)
[<img alt="Off-White Off-White Arrows Hoodie Black" src="https://process.fs.grailed.com/AJdAgnqCST4iPtnUxiGtTz/cache=expiry:max/rotate=deg:exif/resize=width:480,height:640,fit:crop/output=format:webp,quality:70/compress/https://cdn.fs.grailed.com/api/file/9CMvJoQIRaqgtK0u9ov0"/>]
[]
[]
[]
[]
(...many more empty lists...)

1 个答案:

答案 0 :(得分:3)

该网站似乎正在使用JavaScript加载数据。请尝试使用Selenium和漂亮的汤。

from bs4 import BeautifulSoup
from selenium import webdriver

url = "https://www.grailed.com/shop/EkpEBRw4rw"
browser = webdriver.Chrome(executable_path="/path/to/chromedriver.exe")
browser.get(url)
soup = BeautifulSoup(browser.page_source,"html.parser")
items=soup.select(".listing-cover-photo ")
print(items)