首页 > 解决方案 > Python:无法使用 Beautifulsoup 获得任何输出

问题描述

我正在尝试从任何随机网站上抓取一些单词,但是当我尝试打印结果时,以下程序没有显示错误并且没有显示任何输出。

我已经检查了两次代码,甚至合并了一个 if 语句来查看程序是否正在获取任何单词。


    import requests
    import operator
    from bs4 import BeautifulSoup
        
        
    def word_count(url):

        wordlist = []

        source_code = requests.get(url)

        source = BeautifulSoup(source_code.text, features="html.parser")

        for post_text in source.findAll('a', {'class':'txt'}):
            word_string=post_text.string

            if word_string is not None:
                word = word_string.lower().split()

                for each_word in word:
                    print(each_word)
                    wordlist.append(each_word)

                else:
                    print("None")
    
    word_count('https://mumbai.craigslist.org/')

我期望“class = txt”下的所有单词都显示在输出中。

标签: pythonpython-3.xbeautifulsoup

解决方案


OP我希望类文本的所有单词都显示在输出中

罪魁祸首

for post_text in source.findAll('a', {'class':'txt'}):

原因

锚标签没有类txt,但它里面的跨度标签有。

因此

import requests
from bs4 import BeautifulSoup

def word_count(url):
    source_code = requests.get(url)
    source=BeautifulSoup(source_code.text, features="html.parser")

    for post_text in source.findAll('a'):
        s_text = post_text.find('span', class_ = "txt")
        if s_text is not None:
            print(s_text.text)

word_count('https://mumbai.craigslist.org/')

输出

community
activities
artists
childcare
classes
events
general
groups
local news
lost+found
missed connections
musicians
pets
.
.
.

推荐阅读