【问题标题】:How to extract the strong elements which are in div tag如何提取div标签中的强元素
【发布时间】:2016-08-21 22:44:55
【问题描述】:

我是网络抓取的新手。我正在使用 Python 来抓取数据。 有人可以帮助我如何从以下位置提取数据:

<div class="dept"><strong>LENGTH:</strong> 15 credits</div>

我的输出应该是 LENGTH:15 credits

这是我的代码:

from urllib.request import urlopen
from bs4 import BeautifulSoup 

length=bsObj.findAll("strong")
for leng in length:
    print(leng.text,leng.next_sibling)

输出:

DELIVERY:  Campus
LENGTH:  2 years
OFFERED BY:  Olin Business School

但我希望只有 LENGTH。

网址:http://www.mastersindatascience.org/specialties/business-analytics/

【问题讨论】:

    标签: python web-scraping beautifulsoup


    【解决方案1】:

    你应该改进你的代码来定位strong元素通过文本

    soup.find("strong", text="LENGTH:").next_sibling
    

    或者,对于多个长度:

    for length in soup.find_all("strong", text="LENGTH:"):
        print(length.next_sibling.strip())
    

    演示:

    >>> import requests
    >>> from bs4 import BeautifulSoup
    >>>
    >>> url = "http://www.mastersindatascience.org/specialties/business-analytics/"
    >>> response = requests.get(url)
    >>> soup = BeautifulSoup(response.content, "html.parser")
    >>> for length in soup.find_all("strong", text="LENGTH:"):
    ...     print(length.next_sibling.strip())
    ... 
    33 credit hours
    15 months
    48 Credits
    ...
    12 months
    1 year
    

    【讨论】:

      【解决方案2】:

      如果有人还在寻找这个,这里是示例: age = soup.find('div', class_ = 'item-birthday').find('strong').get_text() 这意味着,获取 div 内的强元素。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-01-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-11-22
        相关资源
        最近更新 更多