python - 条件语句在我的抓取工具中表现得很奇怪

标签 python python-3.x if-statement web-scraping

我编写了一个 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/

相关文章:

python - Python 单元测试套件

c++ - For 循环条件(整数 vector )。如何获取之前的值?

c - If 语句条件中的二元 AND 运算符

python - 对 Python 类和实例变量的复合赋值

python - 如何用Python中的其他值替换文件中的值

Python - 导入 Scipy 时出错

python - 如何从一门类(class)切换到另一门类(class)?

python - 将数组的 Python 字典转换为数据框

python - 将迭代转化为递归

javascript - 为什么这个 if 语句在 for 循环内创建一个未定义的值?