【问题标题】:Getting a AttributeError: ResultSet object has no attribute 'prettify'. while using BeautifulSoup获取 AttributeError:ResultSet 对象没有属性“美化”。使用 BeautifulSoup 时
【发布时间】:2021-04-20 04:46:01
【问题描述】:

我正在尝试获取页面的 html,但它显示为列表的第二个值↓。

Traceback (most recent call last):
  File "E:\mycodes\python codes\testcode.py", line 14, in <module>
    print(soup.prettify())
  File "C:\Users\sonug\AppData\Local\Programs\Python\Python36-32\lib\site-packages\bs4\element.py", line 2161, in __getattr__
    "ResultSet object has no attribute '%s'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?" % key
AttributeError: ResultSet object has no attribute 'prettify'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

它成功打印了第一页的 html 代码,只是没有打印列表的第二个值。

这是我的代码:-

from bs4 import BeautifulSoup as soup
import requests

USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
session = requests.Session()
session.headers['User-Agent'] = USER_AGENT

query=['who is the president of India','who is the president of usa']

for query in query:
    url=f"https://www.google.com/search?q={query}"
    html = session.get(url).text
    soup = soup(html,'html.parser')
    print(soup.prettify())

【问题讨论】:

  • 把你的变量名改成其他的result = soup(html,'html.parser')

标签: python beautifulsoup python-requests


【解决方案1】:

在您的第一次迭代中,您使用在 html 上调用它的输出覆盖了您命名为 soup 的 BeautfulSoup。 在第二次迭代中,变量soup 不再指向BeautifulSoup,而是指向第一次迭代的输出,所以事情变得一团糟。

from bs4 import BeautifulSoup as soup
import requests

USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.157 Safari/537.36"
session = requests.Session()
session.headers['User-Agent'] = USER_AGENT

queries=['who is the president of India','who is the president of usa']

for query in queries:
    url=f"https://www.google.com/search?q={query}"
    html = session.get(url).text
    soup_result = soup(html,'html.parser')
    print(soup_result.prettify())

【讨论】:

    【解决方案2】:

    您应该在结果集中使用汤,而应该使用另一个变量来代替它。

    喜欢结果或其他。

    试试这个:-

    result = soup(html,'html.parser')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-09
      • 2018-09-12
      • 1970-01-01
      • 2016-06-28
      • 1970-01-01
      • 1970-01-01
      • 2023-04-05
      • 1970-01-01
      相关资源
      最近更新 更多