【问题标题】:Scrape Product Image with BeautifulSoup (Error)使用 BeautifulSoup 抓取产品图像(错误)
【发布时间】:2021-07-04 09:25:52
【问题描述】:

我需要你的帮助。我正在开发一个电报机器人,它将亚马逊的所有销售额发送给我。 它运行良好,但此功能无法正常运行。我总是遇到同样的错误,但是会阻止脚本

imgs_str = img_div.img.get('data-a-dynamic-image') # 一个Json格式的字符串 AttributeError: 'NoneType' 对象没有属性 'img'

 def take_image(soup):
    
    img_div = soup.find(id="imgTagWrapperId")

    imgs_str = img_div.img.get('data-a-dynamic-image')  # a string in Json format

    # convert to a dictionary
    imgs_dict = json.loads(imgs_str)
    #each key in the dictionary is a link of an image, and the value shows the size (print all the dictionay to inspect)
    num_element = 0 
    first_link = list(imgs_dict.keys())[num_element]
    return first_link 

我仍然不明白如何解决这个问题。 谢谢大家!

【问题讨论】:

    标签: python-3.x beautifulsoup telepot


    【解决方案1】:

    从错误的外观来看,soup.find 不起作用。 您是否尝试过使用images = soup.findAll("img",{"id":"imgTagWrapperId"}) 这将返回一个列表

    【讨论】:

      【解决方案2】:

      图片不会插入到 HTML 页面中,它们会链接到它,因此您需要等到上传。这里我给你两个选择;

      1-)(不推荐,因为可能存在误差)简单;您可以等到图像加载完毕(为此您可以使用“time.sleep()”

      2-)(推荐)我宁愿使用Selenium Web Driver。使用 selenium 时也需要等待,但好在 selenium 对这项工作有独特的功能。 我将展示如何用硒制作它;

      from selenium import webdriver
      from selenium.webdriver.support.ui import WebDriverWait
      from selenium.webdriver.support import expected_conditions as EC
      from selenium.webdriver.common.by import By
      from selenium.common.exceptions import TimeoutException
      
      browser = webdriver.Chrome()
      browser.get("url")
      delay = 3 # seconds
      try:
          myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'imgTagWrapperId')))# I used what do you want find
          print ("Page is ready!")
      except TimeoutException:
          print ("Loading took too much time!")
      

      更多文档

      Code example for way 1

      Q/A for way 2

      【讨论】:

      • 非常感谢您的回答,但我有一个问题要问您。它适用于所有目标吗?价格、标题、照片、折扣等?还是只用于照片?
      • @Giuseppe,你可以使用 selenium 模块你想知道什么。 Selenium 在 Internet 上可用于多种用途,它还可以有效地查找加载了您上面提到的 java 脚本的文件,您只需要知道/学习如何使用它。我留下了上面文件的链接,请查看更多。祝你好运:)
      • 尝试你的草图,myElem 不起作用,所以我只打印我认为的位置,而不是文本。我现在该怎么办?
      猜你喜欢
      • 2022-08-14
      • 2022-08-18
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多