首页 > 解决方案 > BS4 (BeautifulSoap) - AttributeError: 'NoneType' 对象没有属性 'getText'

问题描述

我一直在这里研究,我为我的问题找到的解决方案无法解决。

我正在尝试创建捕获产品名称和价格的亚马逊页面的抓取,但是当我尝试运行它时,我总是收到错误消息:

AttributeError:“NoneType”对象没有属性“getText”

我觉得奇怪的是,这个错误是间歇性的,时间有效,时间会出现错误,我相信这是渲染肥皂内容的时间以外的其他方式。

我已经尝试使用 time.sleep 几秒钟来尝试规避这个问题,但没有成功......

这是我的代码的摘录:

import requests
import time
from bs4 import BeautifulSoup

def 商店亚马逊():

URL = ['www.amazon.com.br/Notebook-Acer-AN515-54-58CL-Endless-GTX1650/dp/B0883VMXX4?ref_=Oct_s9_apbd_otopr_hd_bw_bHrUqLT&pf_rd_r=1ZG49PCAZV8RN8CK6QDQ&pf_rd_p=ae2a6e14-5e57-57d1-a7c7-38f2deae6a08&pf_rd_s=merchandised-search-10&pf_rd_t=BROWSE&pf_rd_i=16364755011','www.amazon.com.br/Monitor-Gamer-Samsung-LS24D332HSX-ZD/dp/B07MVPD3VK?ref_=Oct_s9_apbd_otopr_hd_bw_bHrUqbb&pf_rd_r=D34JDZ7EBFS7CTZ3X5CW&pf_rd_p=dfd6eead-be55-57b6-bdaf-226199170f0a&pf_rd_s=merchandised-search-10&pf_rd_t=BROWSE&pf_rd_i=16364756011']

headers = {'User-Agent': 'Mozilla/5.0 (X11; Fedora; Linux x86_64; rv:83.0) Gecko/20100101 Firefox/83.0'}

for x in range(len(URL)):
    time.sleep(1)
    page = requests.get(URL[x], headers=headers)
    soup = BeautifulSoup(page.content, 'lxml')

    productName  = soup.find('span', {'id':'productTitle'}).getText()
    productPrice = soup.find('span', {'id':'priceblock_ourprice'}).getText()

    print (productName.strip())
    print (productPrice)
    print() 
    # converted_price = float(productPrice[0:5])
    # print (converted_price)

        

商店亚马逊()

标签: python-2.7soapbeautifulsoup

解决方案


我打印了您的代码提供的汤。亚马逊检测到这是一次自动尝试并提供了此通知

要讨论对 Amazon 数据的自动访问,请联系 api-services-support@amazon.com。有关迁移到我们 API 的信息,请参阅 https://developer.amazonservices.com/ref=rm_c_sv 上的 Marketplace API ,或https://affiliate-program.amazon.com/gp/advertising/api上的产品广告 API /detail/main.html/ref=rm_c_ac用于广告用例。

我仍然可以使用 selenium 获取它:

URL = ['https://www.amazon.com.br/Notebook-Acer-AN515-54-58CL-Endless-GTX1650/dp/B0883VMXX4']

for x in range(len(URL)):
    soup = return_page_source_soup(URL[x])
    # print(soup)
    productName  = soup.find('span', {'class':'product-title-word-break'}).get_text(strip=True)
    print (productName)

这是我将源代码从 selenium 传输到 BeautifulSoup 的代码

from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.common.exceptions import TimeoutException

chromeOptions = Options()
chromeOptions.headless = False
PATH = "D:\chromedriver.exe"
driver = webdriver.Chrome(PATH, options=chromeOptions)
driver.set_page_load_timeout(20)

def return_page_source_soup(link):
    # pass
    while True:
        try:
            driver.get(link)
        except TimeoutException:
            print("timeout, retrying")
            continue
        else:
            break

    response = driver.page_source
    soup = BeautifulSoup(response,"lxml")
    return soup

注意 1:您在 URL 中插入参考 ID。这不是一成不变的。您必须从 URL中的?ref中删除。

注 2:亚马逊有一个附属计划。所以,我认为您不需要以这种方式从亚马逊抓取数据。


推荐阅读