gpt4 book ai didi

python - 使用 beautifulsoup 从 craigslist 获取价格

转载 作者:太空宇宙 更新时间:2023-11-04 01:28:50 24 4
gpt4 key购买 nike

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

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 prices == "": 更改为 if prices == [] 一切都应该没问题。

希望对您有所帮助。

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com