【问题标题】:Extracting Text from Span Tag using BeautifulSoup使用 BeautifulSoup 从 Span 标签中提取文本
【发布时间】:2021-09-05 23:51:58
【问题描述】:

我正在尝试从此网址中提取估计的每月费用“$1,773”:

https://www.zillow.com/homedetails/4651-Genoa-St-Denver-CO-80249/13274183_zpid/

在检查页面的该部分时,我看到了以下数据:

<div class="sc-qWfCM cdZDcW">
   <span class="Text-c11n-8-48-0__sc-aiai24-0 dQezUG">Estimated monthly cost</span>
   <span class="Text-c11n-8-48-0__sc-aiai24-0 jLucLe">$1,773</span></div>

为了提取 1,773 美元,我试过这个:

from bs4 import BeautifulSoup
import requests

url = 'https://www.zillow.com/homedetails/4651-Genoa-St-Denver-CO-80249/13274183_zpid/'
headers = {"User-Agent": "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0"}

soup = BeautifulSoup(requests.get(url, headers=headers).content, "html")

print(soup.findAll('span', {'class': 'Text-c11n-8-48-0__sc-aiai24-0 jLucLe'}))

这会返回一个包含三个元素的列表,但没有提及 $1,773。

[<span class="Text-c11n-8-48-0__sc-aiai24-0 jLucLe">$463,300</span>, 
<span class="Text-c11n-8-48-0__sc-aiai24-0 jLucLe">$1,438</span>, 
<span class="Text-c11n-8-48-0__sc-aiai24-0 jLucLe">$2,300<!-- -->/mo</span>]

谁能解释一下如何退回 1,773 美元?

【问题讨论】:

    标签: html web-scraping beautifulsoup zillow


    【解决方案1】:

    我认为你必须找到第一个父元素。 例如:

    parent_div = soup.find('div', {'class': 'sc-fzqBZW bzsmsC'})
    result = parent_div.findAll('span', {'class': 'Text-c11n-8-48-0__sc-aiai24-0 jLucLe'})
    
    

    【讨论】:

    • 谢谢!对您的第一行代码进行一些编辑确实会返回成本,但它的值不是 1773 美元(即使共享的 URL 中不存在这个值,它也会给出 1438 美元的输出)。 “soup.findAll('div', {'class': 'sc-qWfCM cdZDcW'})[0].contents[1].contents[0]”。我已经用可重现的代码更新了我的问题。
    • 谢谢!我试过了,但 parent_div 没有返回。此外,我还更新了问题,其中包含共享网址中“$1773”的每月费用快照,以供参考。
    • 我确实试过你的代码。但我收到机器人页面错误。
    • 你有 $kype 吗?直播:.cid.626f9a797d9b6ef9
    • 我正在等待您的联系。我可以帮你。
    【解决方案2】:

    在解析网页时,我们需要以呈现方式分离页面的组件。有些组件是静态或动态渲染的。动态内容也需要一些时间来加载,因为页面需要某种后端 API。

    Read more here

    我尝试使用 Selenium ChromeDriver 解析您的页面

    import time
    
    from selenium import webdriver
    from selenium.webdriver.common.by import By
    
    driver = webdriver.Chrome()
    driver.get("https://www.zillow.com/homedetails/4651-Genoa-St-Denver-CO-80249/13274183_zpid/")
    time.sleep(3)
    time.sleep(3)
    el = driver.find_elements_by_xpath("//span[@class='Text-c11n-8-48-0__sc-aiai24-0 jLucLe']")
    
    for e in el:
        print(e.text)
    
    time.sleep(3)
    driver.quit()
    
    #OUTPUT
    $463,300
    $1,773
    $2,300/mo
    

    【讨论】: