python - 使用 beautifulsoup 从 craigslist 获取价格

标签 python python-2.7 beautifulsoup craigslist

我是 python 编码新手(可能需要几天),基本上是在 stackoverflow 上学习其他人的代码。我试图编写的代码使用 beautifulsoup 来获取 craigslist 上摩托车的 pid 和相应价格。我知道还有很多其他方法可以做到这一点,但我当前的代码如下所示:

from bs4 import BeautifulSoup         
from urllib2 import urlopen               
u = ""
count = 0
while (count < 9):
    site = "http://sfbay.craigslist.org/mca/" + str(u)
    html = urlopen(site)                      
    soup = BeautifulSoup(html)                
    postings = soup('p',{"class":"row"})                      
    f = open("pid.txt", "a")
    for post in postings:
        x = post.getText()
        y = post['data-pid']
        prices = post.findAll("span", {"class":"itempp"})
        if prices == "":
            w = 0
        else:
            z = str(prices)
            z = z[:-8]
            w = z[24:]
        filewrite = str(count) + " " + str(y) + " " +str(w) + '\n'
        print y
        print w
        f.write(filewrite)
    count = count + 1 
    index = 100 * count
    print "index is" + str(index)
    u = "index" + str(index) + ".html"

它工作得很好,随着我不断学习,我计划对其进行优化。我现在遇到的问题是,没有价格的条目仍然出现。我是否缺少一些明显的东西? 谢谢。

最佳答案

问题在于您如何比较价格。你说:

prices = post.findAll("span", {"class":"itempp"})

在 BS .findAll 中返回一个元素列表。当您将价格与空字符串进行比较时,它将始终返回 false。

>>>[] == ""
False

if rates == "": 更改为 if rates == [] ,一切都应该没问题。

我希望这会有所帮助。

关于python - 使用 beautifulsoup 从 craigslist 获取价格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15554311/

相关文章:

python - django 模型 select_lated 或 prefetch_lated 子模型

apache - Python mkdir 错误所有者

python - 使用 beautifulsoup 抓取动态网站

python - 使用 BeautifulSoup 在 python 中抓取多个页面

python - 使用 Beautifulsoup 从网站中提取数据

python - 检测字符串中的 URL 并用 "<a href..."标记包装

python - 从图像数据库中查找图像

python - 为每个唯一的 id 收集 python 中 csv 的所有值

python - openpyxl - 能够从图表中删除边框吗?

python - importError python while import exists and Pycharm recognize it