我想刮一些东西作为我的第一个程序,只是为了真正学习的基础知识,但我有麻烦显示不止一个结果。你知道吗
前提是去一个论坛(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
正如你所看到的,它正在检查“免费”这个词,它可以工作,但它只显示第一个结果,而页面中还有几个。你知道吗
默认情况下,字符串比较区分大小写(
FREE != free
)。要解决您的问题,首先需要将test2
小写:要解决问题并简化代码,请尝试以下操作:
奖金:打印
href
的值:另见this。你知道吗
相关问题 更多 >
编程相关推荐