0

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

imgs_str = img_div.img.get('data-a-dynamic-image') # 一个 Json 格式的字符串 AttributeError: 'NoneType' object has no attribute '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 

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

4

2 回答 2

0

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

于 2021-07-04T09:33:36.900 回答
0

图片没有插入 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!")

更多文档

方式 1 的代码示例

方式 2 的问答

于 2021-07-09T21:31:00.373 回答