我有一个bs4在craigslist上报废了二手车。现在它返回所有帖子,但我试图获取少于$ 2k的帖子。我知道我要么需要嵌套的if语句,要么需要单独的函数。有什么帮助吗?

# Loop through returned results
for result in results:
    # Error handling
    try:
        # Identify and return title of listing
        title = result.find('a', class_="result-title").text
        # Identify and return price of listing
        price = result.a.span.text
        # Identify and return link to listing
        link = result.a['href']

        # Print results only if title, price, and link are available
        if (price and title and link):
            print('-------------')
            print(title)
            print(price)
            print(link)
        next
    except AttributeError as e:
        print(e)

最佳答案

您可以检查是否使用int(price) >= 2_000,如果使用continue,则跳过打印:

for result in results:
    title = result.find('a', class_="result-title").text
    price = result.a.span.text
    link = result.a['href']

    try:
        if int(price) >= 2_000:
            continue
    except ValueError:
        continue


    if all(price, title, link):
        print('-------------')
        print(title, price, link, sep='\n')

关于python - 如何从craigslist中仅抓取小于x的价格,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56927630/

10-10 18:57