python - 如何从 craigslist 中仅抓取低于 x 的价格

标签 python beautifulsoup

我有一辆 bs4 在 craigslist 上抓取二手车。现在它返回所有帖子,但我试图获得低于 2000 美元的帖子。我知道我要么需要一个嵌套的 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,如果使用继续则跳过打印:

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/

相关文章:

python - 在 SQLAlchemy 中,如何在提交调试之前预览 SQL 语句?

python - 在 Python 中将 Qt 图像转换为 Open CV 中的图像

python - 我可以使用 Pandas 的 pivot_table 聚合缺失值的列吗?

python - 来自 Yelp API 的错误请求

Python 线程通信不起作用

python - 如何使用beautifulsoup检查字符串是否存在

python - 抓取中间有 <br> 的表格(不出现)

python - 获取 BeautifulSoup 中父项的第一个文本实例

python:从很长的div类输出中选择特定部分

asp.net - 如何使用 python 请求和 BeautifulSoup 在 Aspx 动态网站中循环下拉菜单并抓取数据