【问题标题】:ResultSet object has no attribute 'get'ResultSet 对象没有属性“get”
【发布时间】:2020-03-08 12:37:36
【问题描述】:

您好,我目前正在尝试使用 beautifulsoup 抓取此 https://www.sec.gov/ix?doc=/Archives/edgar/data/1090727/000109072720000003/form8-kq42019earningsr.htmSEC 链接以获取包含“UPS”的链接

pressting = soup3.find_all("a", string="UPS")
linkkm = pressting.get('href')
print(linkkm)

但是当我这样做时,我得到了这个错误:

Traceback (most recent call last):
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\SEC.py", line 55, in <module>
    print('Price: ' + str(edgar()))
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\SEC.py", line 46, in edgar
    linkkm = pressting.get('href')
  File "C:\Users\Admin\AppData\Local\Programs\Python\Python36\lib\site-packages\bs4\element.py", line 2081, 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 'get'. You're probably treating a list of elements like a single element. Did you call find_all() when you meant to call find()?

我的预期结果是提取 href,然后打印该 href。任何帮助将不胜感激。

【问题讨论】:

标签: python web-scraping beautifulsoup


【解决方案1】:

页面加载后基本上通过JavaScript 动态呈现。因此,在您首先渲染它之前,您将无法解析这些对象。因此requests 模块不会渲染JavaScript

您可以使用selenium 方法来实现这一点。否则,您可以使用 html_request 模块中的 HTMLSession 即时渲染它。

from selenium import webdriver
from selenium.webdriver.firefox.options import Options
from bs4 import BeautifulSoup
import re
from time import sleep

options = Options()
options.add_argument('--headless')
driver = webdriver.Firefox(options=options)

driver.get("https://www.sec.gov/ix?doc=/Archives/edgar/data/1090727/000109072720000003/form8-kq42019earningsr.htm")

sleep(1)
soup = BeautifulSoup(driver.page_source, 'html.parser')

for item in soup.findAll("a", style=re.compile("^text")):
    print(item.get("href"))

driver.quit()

输出:

https://www.sec.gov/Archives/edgar/data/1090727/000109072720000003/exhibit991-q42019earni.htm
https://www.sec.gov/Archives/edgar/data/1090727/000109072720000003/exhibit992-q42019finan.htm

但是,如果您只想要第一个网址;

url = soup.find("a", style=re.compile("^text")).get("href")
print(url)

输出:

https://www.sec.gov/Archives/edgar/data/1090727/000109072720000003/exhibit991-q42019earni.htm

【讨论】:

  • 谢谢解答 有没有可能提高速度?
  • @DaRealHeroofHell 该问题取决于您的环境和运行代码的位置。你可以使用requests_html 模块。你要解析多个网址吗?
  • @DaRealHeroofHell from requests_html import HTMLSession 会很适合你
【解决方案2】:

您的问题是,soup3.find_all() 返回一个结果列表,而您试图在此列表上使用 .get() 方法,而您应该只在一个项目上使用它。

尝试遍历它们并打印每一个:

pressting = soup3.find_all("a", string="UPS")
for i in pressting:
    print(i.get('href'))

【讨论】:

  • 您好,这也不起作用。这是它给我的错误:
  • @DaRealHeroofHell 我编辑了我的答案,试试看。
  • 这不会返回任何东西
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-08-06
  • 2017-07-22
  • 1970-01-01
  • 2016-12-19
  • 2013-03-30
  • 1970-01-01
  • 2016-11-25
相关资源
最近更新 更多