我编写了一个 python 脚本,在 for 循环
中使用两个条件语句来检查下一页 url 在某个网页中是否可用。如果链接可用,脚本应该打印该链接。但是,如果没有这样的链接,则应执行 else
block 并打印此行 No link is There
。
当我运行下面的脚本时,它仅在可用时打印链接(位于 if
block 内),但当没有此类链接时,它永远不会执行 else
阻止并退出(也没有错误)。
顺便说一句,我希望保留 for 循环
并使我的脚本打印 else
block 内的语句。我怎样才能这样做?
这是脚本:
import requests
from bs4 import BeautifulSoup
keyword = ["coffee","uranium"] #the keyword uranium when gets passed to the function it is supposed to execute the else block
url = "https://www.yelp.com/search?find_desc={}&find_loc=San+Francisco"
def check_link(link,query):
res = requests.get(link.format(query))
soup = BeautifulSoup(res.text,"lxml")
for link in soup.select(".pagination-links .next"):
if link:
print(link.get("href"))
else:
print("No link is there")
if __name__ == '__main__':
for item in keyword:
check_link(url,item)
最佳答案
当选择器没有匹配项时,soup.select()
返回一个空列表。没有什么可以循环的,所以你永远不会到达if
。它不会返回包含任何 None
元素的列表。
您应该测试它返回的列表的长度:
links = soup.select(".pagination-links .next")
if links:
for link in links:
print(link.get("href"))
else:
print("No link is there")
关于python - 条件语句在我的抓取工具中表现得很奇怪,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50866537/