无法在BeautifulSoup中获取一些细节

2024-10-03 17:19:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用BeautifulSoup来scrpe数据,所有的东西都在我的代码中工作,除了一件事,那就是价格。我试图刮一个房地产网站,但无法刮的价格.网站是“https://www.proptiger.com/all-projects

以下是我的代码:

from urllib.request import urlopen
from bs4 import BeautifulSoup
import requests
import time
import json
import io
url = "https://www.proptiger.com/all-projects"
# for all pages https://www.proptiger.com/all-projects?page=2
html = urlopen(url)
soup = BeautifulSoup(html, "html.parser")
container = soup.find_all("section", {"class":"project-card-main-wrapper"})  
print(len(container))

newFile = "Prop_Data.csv"
f = open(newFile, "w", encoding = "utf-8")
Headers = "Project, Url, City, Builder, Price\n"
f.write(Headers)
#f.close()

for i in container:
    contain = i.find_all("div", {"class":"proj-name"})
    project_name = contain[0]['title']
    url2 = i.div['data-url']
    url1 = "https://www.proptiger.com"
    url = url1+url2
    get_city = i.find_all("span", {"itemprop":"address"})#or by div, {"class":"loc"}
    city  = get_city[0]["title"]# or by getcity.text
    builder = i.find_all("div", {"class":"projectBuilder put-ellipsis"})
    bName = builder[0].text
    price = i.find_all("div", {"class":"project-price"})
    pricereal = price[0].text#not able to print the print says list out of index
    print(pricereal)
    #f.write("{}".format(project_name) +",{}".format(url)+",{}".format(city)+",{}".format(bName)+"\n")
 #f.close()

现在,每当我运行这个代码时,它都会显示列表超出范围。你知道吗

以下是价格:

<div class="project-price" itemscope="" itemtype="https://schema.org/PriceSpecification"><span itemprop="minPrice">₹ 32.4 L</span><span itemprop="maxPrice">- ₹ 88.0 L</span> <!-- -if(project.avgPricePerUnitArea)div.text-right.price-perunit &#8377; / sq ft--> </div>

我想要最低价格和最高价格,所以我做文本,得到56=-6个项目的价格,然后列出超出范围。有人知道我做错了什么吗?你知道吗


Tags: httpsimportdivprojectcomurlwww价格
3条回答

当你刮取不可用的信息时,你会得到那个错误。如果您正在查找价格,但没有显示特定项目的值,则会显示错误并中断代码。它被破坏是因为你的代码说那里有东西,而实际上没有

解决这个问题的方法是使用try-except语句。你知道吗

try:
    pricereal = price[0].tex
except:
    pricereal = "n/a"

你没有得到这个价格,因为它在javascript中。别搞混了,其他的东西都印出来了,为什么价格没有印出来呢。因此,为了解决这一问题,你可以将硒与美素结合使用。你知道吗

我在这里使用了代码的必要部分:

from bs4 import BeautifulSoup
from selenium import webdriver
import time

driver = webdriver.Chrome()
driver.get("https://www.proptiger.com/all-projects")
time.sleep(5)
soup = BeautifulSoup(driver.page_source, "html.parser")
driver.quit()

for item in soup.find_all("section", {"class":"project-card-main-wrapper"}):
    price = item.select(".project-price")[0].text if item.select(".project-price") else ""
    print(price)

部分结果:

₹ 32.4 L- ₹ 88.0 L
₹ 33.6 L- ₹ 51.0 L
₹ 62.0 L- ₹ 1.25 Cr
₹ 49.9 L- ₹ 1.32 Cr
₹ 35.0 L- ₹ 50.0 L

为了让事情更清楚,请看下面:

>>> import requests
>>> link = "https://www.proptiger.com/all-projects"
>>> page = requests.get(link).text
>>> 'Umang Premiere' in page
True
>>> '₹ 35.0 L' in page
False
>>> 

我是用pythonide做的。正如你所看到的,产品名称被找到了,但价格却没有。这是因为javascript。希望有道理。你知道吗

因为其中一个项目(Godrej Emerald)按要求有价格,因此没有价格价值。你知道吗

相关问题 更多 >