【问题标题】:Scraping the Location from a Real Estate Website: I am trying to scrap out the 'location' but it brings out the same output as the 'title'从房地产网站刮取位置:我试图刮掉“位置”,但它会产生与“标题”相同的输出
【发布时间】:2022-10-07 14:19:10
【问题描述】:
import pandas as pd
import requests
from bs4 import BeautifulSoup
from time import sleep
from random import randint

data = []
for page in range(0,2):
    print(page)
    page = requests.get(\"https://www.propertypro.ng/property-for-rent/commercial-property/office-space/in/abuja?page=\"+str(page))
    sleep(randint(2,10))

    

    soup = BeautifulSoup(page.content, \'html.parser\')

    
            
    for item in soup.find_all(\'div\', {\'class\': \"single-room-sale\", \'style\': False}):
        data.append({
            \'price\': item.find(\'div\', class_=\"n50\").get_text(strip=True).split(\'/\')[0],
            \'title\': item.find(class_=\"listings-property-title\").get_text(strip=True),
            \'location\': item.find(\'h4\').get_text(strip=True),
            \'contact\': item.find(\'div\', class_=\"phone-icon\").get_text(strip=True) if item.find(\'div\', class_=\"phone-icon\") else None
               

            
        })
df = pd.DataFrame(data)
print(df.to_string())
  • 请阅读How to Ask 并注意这是不是讨论区.您应该首先尝试自己理解问题,并创建一个minimal reproducible example - 不要显示所有代码以尝试创建您想要的结果;显示创建所需的代码显示问题的部分.然后确保问一个问题在帖子本身。它应该以“how”或“why”之类的疑问词开头,并以问号(“?”)结尾。另请阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 并尝试检查代码。例如,您看到 item 的值是多少?

标签: python beautifulsoup


【解决方案1】:

这里的问题是这两个项目都存在于 seperat <h4>find() 只会选择第一个。

所以你必须选择更具体的:

'location': item.select_one('a + h4').get_text(strip=True)

【讨论】:

    猜你喜欢
    • 2015-09-02
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多