【问题标题】:web scraping error while using Beautiful soup and requests in python在python中使用美丽的汤和请求时出现网络抓取错误
【发布时间】:2020-06-16 13:34:46
【问题描述】:

我正在尝试编写跟踪产品亚马逊价格的代码。代码如下

import requests
from bs4 import BeautifulSoup
url='https://www.amazon.com/LunaJany-Womens-Striped-Office-Career/dp/B01DPLT4AC/ref=sxin_7_ac_d_rm?ac_md=2-2-ZHJlc3NlcyBmb3Igd29tZW4gd29yayBjYXN1YWw%3D-ac_d_rm&crid=1POYCFAFYAR8B&cv_ct_cx=dresses+for+women+casual+summer&dchild=1&keywords=dresses+for+women+casual+summer&pd_rd_i=B01DPLT4AC&pd_rd_r=0b613dda-1077-46d2-b403-af7e15840645&pd_rd_w=7Mp2P&pd_rd_wg=rNofK&pf_rd_p=a0516f22-66df-4efd-8b9a-279a864d1512&pf_rd_r=1P30PXW75XA27N3M6VDK&psc=1&qid=1592310609&sprefix=dre%2Caps%2C440&sr=1-3-12d4272d-8adb-4121-8624-135149aa9081'
        header={"user-agent":'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36'}
        page=requests.get(url,headers=header)
        soup1=BeautifulSoup(page.content,"html.parser")
        soup2=BeautifulSoup(soup1.prettify(),"html.parser")
        title=soup2.find(id="productTitle").get_text()
        print(title)

在尝试打印标题时出现错误

Traceback (most recent call last):
  File "C:/Users/Patterns/PycharmProjects/RUBI/Tracks amozon prices.py", line 8, in <module>
    title=soup2.find(id="productTitle").getText()
AttributeError: 'NoneType' object has no attribute 'getText'

谁能帮帮我?

【问题讨论】:

  • 错误显示getText,但您的代码显示get_text(),您使用的是哪一个?
  • 贴出的代码有.get_text(),但错误信息显示你实际上使用的是.getText()。请发布您的真实代码。
  • 很抱歉,之前我用过getText,出现了上面的错误,突然想试试get_text(),但是忘记在这里替换错误了。
  • Traceback(最近一次调用最后):文件“C:/Users/Patterns/PycharmProjects/RUBI/Tracks amozon prices.py”,第 8 行,在 title=soup2.find(id ="productTitle").get_text() AttributeError: 'NoneType' 对象没有属性 'get_text'
  • 大量内容是通过 JavaScript 生成的,这是 BeautifulSoup 所没有的功能。但是你可以通过在源代码中删除 json 对象来获得好运,但不能直接从 HTML 中删除。

标签: python beautifulsoup python-requests html-parser


【解决方案1】:

它说NoneType 没有属性"get_text",这意味着没有找到id 为"productTitle" 的匹配元素,因此返回NoneNone 是一个 NoneType 对象,因此没有 "get_text" 属性。

提示 - 尝试调整 productTitle。我不确定,但它可能不是您尝试跟踪其价格的商品的价格元素。

【讨论】:

    【解决方案2】:

    因为没有像productTitle这样的元素。当您使用 beautifull soup 加载页面内容时,会加载一个机器人检查页面。 像这个。 Robot Check

    只需尝试通过-print(soup2) 打印页面内容,您就会知道错误原因。

    【讨论】:

      猜你喜欢
      • 2018-08-17
      • 2019-05-05
      • 2021-03-30
      • 1970-01-01
      • 1970-01-01
      • 2020-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多