用Python和BeautifulSoup在Javascript中获取图片网址

0 人关注

我正在尝试使用Python和BeautifulSoup从下面的页面中获取产品图片。图片是在javascript里面。我正在使用lxml。我创建了一个简化版本的代码,只关注图片。

我想要的图片网址是 https://lapa.co.za/pub/media/catalog/product/cache/image/700x700/e9c3970ab036de70892d86c6d221abfe/l/e/learn_to_read_l3_b05_tippie_fish_cover.jpg

import json
from bs4 import BeautifulSoup
import requests
headers = {
    'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'
testlink = 'https://lapa.co.za/kinder-en-tienerboeke/leer-my-lees-vlak-1-grootboek-9-tippie-en-die-vis'
r = requests.get(testlink, headers=headers)
soup = BeautifulSoup(r.content, 'lxml')
title = soup.find('h1', class_='page-title').text.strip()
images = soup.find('div', class_='product-img-column')
# html_data = requests.get(testlink).text
# data = json.loads(re.search(r'window.INITIAL_REDUX_STATE=(\{.*?\});', html_data))
print(images)
    
1 个评论
你不能这样做,你需要一些东西来把javascript看成webdrivers,我通常使用selenium。
python
web-scraping
beautifulsoup
lxml
screen-scraping
Schalk Joubert
Schalk Joubert
发布于 2021-11-01
1 个回答
chitown88
chitown88
发布于 2021-11-01
已采纳
0 人赞同

json在 <script> 标签中。只需要把它拉出来。

import json
from bs4 import BeautifulSoup
import requests
import re
headers = {
    'User-Agent': 'Mozilla/5.0 (iPad; CPU OS 12_2 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148'
testlink = 'https://lapa.co.za/kinder-en-tienerboeke/leer-my-lees-vlak-1-grootboek-9-tippie-en-die-vis'
r = requests.get(testlink, headers=headers)
soup = BeautifulSoup(r.content, 'lxml')
title = soup.find('h1', class_='page-title').text.strip()
images = soup.find('div', class_='product-img-column')
script = images.find('script', {'type':'text/x-magento-init'})
jsonStr = re.search(r'<script type=\"text/x-magento-init\">(.*)</script>', str(script), re.IGNORECASE | re.DOTALL).group(1)
data = json.loads(jsonStr)
image_data = data['[data-gallery-role=gallery-placeholder]']['mage/gallery/gallery']['data'][0]
image_url = image_data['full']
#image_url = image_data['img']
print(image_url)