代码之家  ›  专栏  ›  技术社区  ›  Kamikaze_goldfish

使用beautifulsoup获取文本。

  •  1
  • Kamikaze_goldfish  · 技术社区  · 7 年前

    我在使用beautifulsoup删除html而只保留文本时遇到了问题。当我运行它时,我得到了错误 AttributeError: ResultSet object has no attribute 'get_text'. You're probably treating a list of items like a single item. Did you call find_all() when you meant to call find()? 有没有什么方法可以让我在 findAll 在我的 divs

    import requests
    from bs4 import BeautifulSoup
    url = 'https://www.brightscope.com/form-5500/basic-info/107299/Orthopedic-Institute-Of-Pennsylvania/15801790/Orthopedic-Institute-Of-Pennsylvania-401k-Profit-Sharing-Plan/'
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    divs = soup.findAll('span', class_='float-right').get_text()
    
    for each in divs:
        print(each)
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   whackamadoodle3000    7 年前

    试试这个:

    import requests
    from bs4 import BeautifulSoup
    url = 'https://www.brightscope.com/form-5500/basic-info/107299/Orthopedic-Institute-Of-Pennsylvania/15801790/Orthopedic-Institute-Of-Pennsylvania-401k-Profit-Sharing-Plan/'
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    divs = soup.findAll('span', class_='float-right') #not on the collection of elements
    
    for each in divs:
        print(each.get_text()) #get_text goes here on the element
    

    编辑:

    import requests
    from bs4 import BeautifulSoup
    url = 'https://www.brightscope.com/form-5500/basic-info/107299/Orthopedic-Institute-Of-Pennsylvania/15801790/Orthopedic-Institute-Of-Pennsylvania-401k-Profit-Sharing-Plan/'
    page = requests.get(url)
    soup = BeautifulSoup(page.text, 'html.parser')
    divs = [e.get_text() for e in soup.findAll('span', class_='float-right')]
    

    会给你一个字符串格式的div列表