Как открыть все href в классе div? - PullRequest
0 голосов
/ 06 августа 2020

Я новичок в python и всем остальном, и я хочу проанализировать все href в классе div. Моя цель - создать программу, открывающую все ссылки в классе div, чтобы иметь возможность сохранять фотографии, связанные с href.

Ссылка: https://www.opi.com/shop-products/nail-polish-powders/nail-lacquer

Раздел, который я хочу проанализировать, называется "div-id: all_nail_lacquer"

Пока я могу получить все href, и это то, что у меня есть:

import urllib
import urllib.request
from bs4 import BeautifulSoup

theurl = "https://www.opi.com/shop-products/nail-polish-powders/nail-lacquer"
thepage = urllib.request.urlopen(theurl)
soup = BeautifulSoup(thepage, "html.parser")

print(soup.title.text)

nail_lacquer = (soup.find('div', {"id":"all_nail_lacquer"}))

"""
for nail_lacquer in soup.find_all('div'):
    print(nail_lacquer.findAll('a')
"""

for a in soup.findAll('div', {"id":"all_nail_lacquer"}):
    for b in a.findAll('a'):
        print(b.get('href'))

1 Ответ

0 голосов
/ 06 августа 2020

Чтобы распечатать ссылки на изображения (даже изображения в высоком разрешении) и заголовки, вы можете использовать этот скрипт:

import urllib
import urllib.request
from bs4 import BeautifulSoup

theurl = "https://www.opi.com/shop-products/nail-polish-powders/nail-lacquer"
thepage = urllib.request.urlopen(theurl)
soup = BeautifulSoup(thepage, "html.parser")

for img in soup.select('#all_nail_lacquer [typeof="foaf:Image"][data-src]'):
    print(img['data-src'])
    print(img['data-src'].replace('shelf_image', 'photos')) # <-- this is URL to hi-res image
    print(img['title'])
    print('-' * 80)

Печать:

https://www.opi.com/sites/default/files/styles/product_shelf_image/public/baby-take-a-vow-nlsh1-nail-lacquer-22850011001_0_0.jpg?itok=3b2ftHzc
https://www.opi.com/sites/default/files/styles/product_photos/public/baby-take-a-vow-nlsh1-nail-lacquer-22850011001_0_0.jpg?itok=3b2ftHzc
Baby, Take a Vow
--------------------------------------------------------------------------------
https://www.opi.com/sites/default/files/styles/product_shelf_image/public/suzi-without-a-paddle-nlf88-nail-lacquer-22006698188_21_0.jpg?itok=mgi1-rz3
https://www.opi.com/sites/default/files/styles/product_photos/public/suzi-without-a-paddle-nlf88-nail-lacquer-22006698188_21_0.jpg?itok=mgi1-rz3
Suzi Without a Paddle
--------------------------------------------------------------------------------
https://www.opi.com/sites/default/files/styles/product_shelf_image/public/coconuts-over-opi-nlf89-nail-lacquer-22006698189_24_1_0.jpg?itok=yasOZA4l
https://www.opi.com/sites/default/files/styles/product_photos/public/coconuts-over-opi-nlf89-nail-lacquer-22006698189_24_1_0.jpg?itok=yasOZA4l
Coconuts Over OPI
--------------------------------------------------------------------------------
https://www.opi.com/sites/default/files/styles/product_shelf_image/public/no-tan-lines-nlf90-nail-lacquer-22006698190_20_1_0.jpg?itok=ot_cu8c5
https://www.opi.com/sites/default/files/styles/product_photos/public/no-tan-lines-nlf90-nail-lacquer-22006698190_20_1_0.jpg?itok=ot_cu8c5
No Tan Lines
--------------------------------------------------------------------------------


...and so on.

РЕДАКТИРОВАТЬ: Для сохранения изображений на диск вы можете использовать этот скрипт:

import requests
from bs4 import BeautifulSoup

theurl = "https://www.opi.com/shop-products/nail-polish-powders/nail-lacquer"
thepage = requests.get(theurl)
soup = BeautifulSoup(thepage.content, "html.parser")

i = 1
for img in soup.select('#all_nail_lacquer [typeof="foaf:Image"][data-src]'):
    u = img['data-src'].replace('shelf_image', 'photos')
    with open('img_{:04d}.jpg'.format(i), 'wb') as f_out:
        print('Saving {}'.format(u))
        f_out.write(requests.get(u).content)
    i += 1
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...