【问题标题】:AttributeError: 'NoneType' object has no attribute 'text' when using BeautifulSoupAttributeError: 'NoneType' 对象在使用 BeautifulSoup 时没有属性 'text'
【发布时间】:2021-01-01 09:59:46
【问题描述】:

我正在运行 YouTube 教程中的以下代码,但是当我想从 .totalcount 类中获取文本时,我收到了 NoneType Object has no attribute "text" 错误。

事实上,在教程视频中它起作用了。有什么帮助吗?如果在细节上会很棒。提前致谢。

url = "https://newyork.craigslist.org/"
site = requests.get(url)
soup = BeautifulSoup(site.text, "html.parser")

sub_link = soup.select("#jjj0 a")
for l in sub_link:
    jobcat = l.text
    joburl = "https://newyork.craigslist.org/" + l.get("href")
    #print(joburl)
    r = requests.get(joburl)
    soup2 = BeautifulSoup(r.text, "html.parser")
    #for total in soup2.select_one("span", class_ = "totalcount"):
        #print(total)
    total = soup2.select_one(".totalcount").text
    #total  = soup2.find("span", class_ = "totalcount").text.strip()

    print(total)

【问题讨论】:

    标签: python beautifulsoup python-requests


    【解决方案1】:

    我尝试运行您的代码并取消注释joburl 的打印语句。

    在第一次迭代中,它显示

    https://newyork.craigslist.org//d/accounting-finance/search/acc
    

    请注意它在基础部分 https://newyork.craigslist.org 之后有一个双斜线。

    在浏览器中打开它会显示一个 404 Not Found 页面。

    许多网络服务器会(方便地)为您解析 URL 中的多个斜杠 - 从而避免可能出现的此类烦人情况。这个网站好像没有。

    解决方法是去掉这行的尾部斜杠:

    joburl = "https://newyork.craigslist.org/" + l.get("href")
    

    但最好将其从您在文件顶部定义基本url 的位置删除。

    以下作品:

    from bs4 import BeautifulSoup
    
    import requests
    
    url = "https://newyork.craigslist.org"
    site = requests.get(url)
    soup = BeautifulSoup(site.text, "html.parser")
    
    sub_link = soup.select("#jjj0 a")
    for l in sub_link:
        jobcat = l.text
        joburl = url + l.get("href")
        # print(joburl)
        r = requests.get(joburl)
        soup2 = BeautifulSoup(r.text, "html.parser")
        total = soup2.select_one(".totalcount").text
        print(total)
    

    【讨论】:

    • 哦,谢谢。是的,它正在工作。并感谢您的详细回答。你太棒了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2019-04-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多