刮削只返回一个值

2024-09-30 22:25:42 发布

您现在位置:Python中文网/ 问答频道 /正文

我想刮一些东西作为我的第一个程序,只是为了真正学习的基础知识,但我有麻烦显示不止一个结果。你知道吗

前提是去一个论坛(http://blackhatworld.com),刮去所有的线程标题并与一个字符串进行比较。如果它包含“free”这个词,它就会打印出来,否则就不会

以下是当前代码:

import requests from bs4 import BeautifulSoup page = requests.get('https://www.blackhatworld.com/') content = BeautifulSoup(page.content, 'html.parser') threadtitles = content.find_all('a', class_='PreviewTooltip') n=0 for x in range(len(threadtitles)): test = list(threadtitles)[n] test2 = list(test)[0] if test2.find('free') == -1: n=n+1 else: print(test2) n=n+1

这是运行程序的结果: https://i.gyazo.com/6cf1e135b16b04f0807963ce21b2b9be.png

正如你所看到的,它正在检查“免费”这个词,它可以工作,但它只显示第一个结果,而页面中还有几个。你知道吗


Tags: httpstestimport程序comfreepagecontent
2条回答

默认情况下,字符串比较区分大小写(FREE != free)。要解决您的问题,首先需要将test2小写:

test2 = list(test)[0].lower()

要解决问题并简化代码,请尝试以下操作:

import requests
from bs4 import BeautifulSoup

page = requests.get('https://www.blackhatworld.com/')
content = BeautifulSoup(page.content, 'html.parser')
threadtitles = content.find_all('a', class_='PreviewTooltip')

count = 0

for title in threadtitles:
    if "free" in title.get_text().lower():
        print(title.get_text())
    else:
        count += 1

print(count)

奖金:打印href的值:

for title in threadtitles:
    print(title["href"])

另见this。你知道吗

相关问题 更多 >