【问题标题】:why error is displayed with find function为什么使用查找功能显示错误
【发布时间】:2023-01-26 17:22:44
【问题描述】:

web scrapping python 为什么 find 函数的参数显示错误。

我期待它在标签 <span></span> 中打印数据 例如:

<span>APPLE iPhone 14 (Midnight, 128 GB)</span>

我想从 HTML 代码中提取 APPLE iPhone 14 (Midnight, 128 GB)。 网站链接是:https://www.flipkart.com/apple-iphone-14-midnight-128-gb/p/itm9e6293c322a84 代码:

import requests

from bs4 import BeautifulSoup

url="https://www.flipkart.com/apple-iphone-14-midnight-128-gb/p/itm9e6293c322a84"

r=requests.get(url)

html_content=r.content

soup=BeautifulSoup(html_content,"html.parser").prettify()

name=soup.find("span",{"class":"B_NuCI"})

print(name)

错误:

C:\Users\Asus\PycharmProjects\pythonProject9\venv\Scripts\python.exe C:\Users\Asus\PycharmProjects\pythonProject9\main.py 
Traceback (most recent call last):

  File "C:\Users\Asus\PycharmProjects\pythonProject9\main.py", line 7, in <module>
    name=soup.find("span",{"class":"B_NuCI"})
TypeError: slice indices must be integers or None or have an __index__ method

Process finished with exit code 1

【问题讨论】:

标签: python html web-scraping web beautifulsoup


【解决方案1】:

删除 .prettify() 因为它会将您的 BeautifulSoup 对象转换为 string,因此您不再能够按照您尝试的方式访问信息。

prettify() 的目标是帮助您直观地了解您使用的文档的结构。

例子

import requests
soup = BeautifulSoup(
            requests.get('https://www.flipkart.com/apple-iphone-14-midnight-128-gb/p/itm9e6293c322a84').text
        )

soup.find('span', class_='B_NuCI').text

输出

APPLE iPhone 14 (Midnight, 128 GB)

【讨论】:

  • 非常感谢你
  • 但我不明白为什么 prettier() 被删除
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-12
  • 1970-01-01
  • 1970-01-01
  • 2016-09-06
  • 2022-06-13
  • 1970-01-01
相关资源
最近更新 更多