【问题标题】:findall error - NoneType' object has no attribute 'findall'findall 错误 - NoneType' 对象没有属性 'findall'
【发布时间】:2017-07-26 03:45:44
【问题描述】:

我不断收到错误消息“缺少 1 个必需的位置参数:'section_url'”

每次我尝试使用 findall 时都会收到此错误。

刚开始学习python,所以任何帮助都将不胜感激!

from bs4 import BeautifulSoup
import urllib3


def extract_data():

    BASE_URL = "http://www.chicagotribune.com/dining/ct-chicago-rooftops-patios-eat-drink-outdoors-near-me-story.html"

    http = urllib3.PoolManager()
    r = http.request('GET', 'http://www.chicagotribune.com/dining/ct-chicago-rooftops-patios-eat-drink-outdoors-near-me-story.html')
    soup = BeautifulSoup(r.data, 'html.parser')
    heading = soup.find("div", "strong")
    category_links = [BASE_URL + p.a['href'] for p in heading.findAll('p')]
    return category_links
    print(soup)


extract_data()

【问题讨论】:

    标签: python python-3.x web-scraping beautifulsoup web-crawler


    【解决方案1】:

    基于已接受答案的答案,我认为这就是您想要的

    from bs4 import BeautifulSoup
    import urllib3
    
    def extract_data():
    
        BASE_URL = "http://www.chicagotribune.com/dining/ct-chicago-rooftops-patios-eat-drink-outdoors-near-me-story.html"
    
        http = urllib3.PoolManager()
        r = http.request('GET', 'http://www.chicagotribune.com/dining/ct-chicago-rooftops-patios-eat-drink-outdoors-near-me-story.html')
        soup = BeautifulSoup(r.data, 'html.parser')
        heading = soup.select('div strong')
        print(heading)
        category_links = [BASE_URL + p.a['href'] for p in [i for i, x in enumerate(heading) if x == "p"]]
        return category_links
    
    
    print(extract_data())
    

    【讨论】:

    • 如果不是,请分享您期望extract_data() 的输出。
    • 谢谢谢谢!正是我想要的。非常感谢您的帮助!
    【解决方案2】:

    通常,NoneType object has no attribute 类错误意味着上游函数返回了None,然后你没有检查它并尝试访问它的方法:

    stuff = get_stuff()  # this returns None
    stuff.do_stuff()  # this crashes
    

    很可能,库找不到带有soup.find 的标题。尝试改用soup.select('div.strong')。

    关于选择器的更多信息: https://www.crummy.com/software/BeautifulSoup/bs4/doc/#css-selectors

    关于 NoneType 的更多信息: https://docs.python.org/3.6/library/constants.html#None

    【讨论】:

    • 非常感谢您的回复!我试过了,但不幸的是还是同样的错误。每次我尝试使用 findAll 时都会出现此错误。
    猜你喜欢
    • 2013-08-06
    • 1970-01-01
    • 1970-01-01
    • 2013-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多