python - 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”下的所有单词都显示在输出中。
解决方案
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
.
.
.
推荐阅读
- postgresql - Postgres - 选择与前 10 个不同 id 匹配的所有行
- android - 我怎样才能创建这样的快照布局
- search - 使用 QueryBuilder API 但不使用 QueryBuilder servlet 时不推荐使用索引警告
- python - “ImportError:导入 pdftotext 时 DLL 加载失败:找不到指定的模块。”
- reporting-services - 如何将 SSRS 中的列可见性表达式与当年和当月联系起来?
- scala - 将 Scala 案例类转换为 PySpark 模式
- google-bigquery - 集成 BigQuery SubPub 和 Cloud Functions
- python - 如何在plotly python中显示变量的值?
- android-studio - Android Studio 会破坏矢量文件
- python - 以矢量化格式编码数据矩阵