【问题标题】:I was using BeautifulSoup package and I get this attributeError我正在使用 BeautifulSoup 包,我得到了这个属性错误
【发布时间】:2019-12-27 09:45:21
【问题描述】:
import requests
from bs4 import BeautifulSoup

request = requests.get("https://www.jumia.com.ng/ergonomic-office-swivel-chair-universal-mpg200557.html")

content = request.content

soup = BeautifulSoup(content, "html.parser")

element = soup.find("span", {"dir" : "ltr", "data-price" : "", "class" : "-b -ltr -fs24"})

print(element.text)
Traceback (most recent call last):

File "C:/Users/EMMRAWL/PycharmProjects/Price of Chair/scr/app.py", line 9, in <module>

print(element.text)

AttributeError: 'NoneType' object has no attribute 'text'

Process finished with exit code 1

【问题讨论】:

  • .find 如果找不到匹配项,则返回 None。因此,请确保您的匹配项已找到或不像 if element: 这样。
  • 谢谢。所以可能是链接不正确,或者元素字典
  • 我看到了错误
  • element = soup.find("span", {"dir" : "ltr", "data-price" : "", "class" : "-b -ltr -tar -fs24" })
  • 元素字典中“-ltr”和“-fs24”之间有一个“-tar”

标签: python beautifulsoup attributeerror


【解决方案1】:

使用获取输出速度更快的 CSS 选择器。

import requests
from bs4 import BeautifulSoup

request = requests.get("https://www.jumia.com.ng/ergonomic-office-swivel-chair-universal-mpg200557.html")

content = request.content

soup = BeautifulSoup(content, "html.parser")
element=soup.select_one('span.-b.-ltr.-fs24[dir="ltr"][data-price]')
print(element.text)

输出

₦ 16,000

要使用 find() 试试下面的代码。

import requests
from bs4 import BeautifulSoup

request = requests.get("https://www.jumia.com.ng/ergonomic-office-swivel-chair-universal-mpg200557.html")

content = request.content

soup = BeautifulSoup(content, "html.parser")
element = soup.find("span", attrs={"dir" : "ltr",  "data-price" : "" , "class" : "-fs24"})
print(element.text)

输出

₦ 16,000

【讨论】:

    猜你喜欢
    • 2018-04-19
    • 2022-08-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    相关资源
    最近更新 更多