我是 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/