BeautifulSoup: невозможно найти URL-адреса изображения в цикле for - PullRequest
0 голосов
/ 11 апреля 2020

Я пытаюсь очистить веб-сайт с помощью красивого супа + селена и получить URL-адреса их изображений в теге <img> с атрибутом src. Я не хочу пробираться через div class names. Вот что я перебираю:

<img src="https://secure.gravatar.com/avatar/f1fb5ec60129b029e968f0522fe4828c?s=100&amp;d=retro&amp;f=y" alt="" width="55" height="55">

Я хочу получить все URL-адреса под тегом изображения. Вот мой код, который дает мне ошибку:

from bs4 import BeautifulSoup as Soup
from selenium.webdriver.chrome.options import Options
from selenium import webdriver

user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/537.36 (KHTML, like Gecko) ' \
             'Chrome/80.0.3987.132 Safari/537.36'

options = Options()
options.add_argument("--headless")
options.add_argument(f'user-agent={user_agent}')
options.add_argument("--disable-web-security")
options.add_argument("--allow-running-insecure-content")
options.add_argument("--allow-cross-origin-auth-prompt")

driver = webdriver.Chrome(executable_path=r"C:\Users\intel\Downloads\setups\chromedriver.exe", options=options)
driver.get("https://python-forum.io/Thread-Using-beautiful-soup-to-get-html-attribute-value")

page = Soup(driver.page_source, features='html.parser')
divs = page.select("img")
for product in divs:
    ele = divs.find('src') 
    print(ele)

Это дает мне ошибку атрибута:

AttributeError: ResultSet object has no attribute 'find'. 
You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

Любая ваша помощь будет принята с благодарностью .. .

Ответы [ 2 ]

1 голос
/ 11 апреля 2020
import requests
from bs4 import BeautifulSoup


def main(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')
    target = [item['content']
              for item in soup.findAll("meta", {'property': "og:image"})]
    print(target)


main("https://python-forum.io/Thread-Using-beautiful-soup-to-get-html-attribute-value")

Выход:

['https://python-forum.io/images/facebook.png', 'https://secure.gravatar.com/avatar/f1fb5ec60129b029e968f0522fe4828c?s=100&d=retro&f=y']
1 голос
/ 11 апреля 2020

Intitaly Я думал, что ele = divs.find('src') должно быть ele = product.find('src'), но это не сработало, поэтому я реализовал его следующим образом. Измените

page = Soup(driver.page_source, features='html.parser')
divs = page.select("img")
for product in divs:
    ele = divs.find('src') 
    print(ele)

на

page = Soup(driver.page_source, features='html.parser')
divs = page.find_all("img")
print(divs)
for product in divs:
    ele = product['src']
    print(ele)

. Это должно дать вам значения в атрибуте sr c тега img.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...