How to extract the strong elements which are in div tag

南笙酒味 提交于 2020-01-24 11:33:33

问题


I am new to web scraping. I am using Python to scrape the data. Can someone help me in how to extract data from:

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

My output should be LENGTH: 15 credits

Here is my code:

from urllib.request import urlopen
from bs4 import BeautifulSoup 

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

Output:

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

but I would like to have only LENGTH.

Website: http://www.mastersindatascience.org/specialties/business-analytics/


回答1:


You should improve your code a bit to locate the strong element by text:

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

Or, for multiple lengths:

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

Demo:

>>> 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:


If someone still looks for this, here is the example: age = soup.find('span', class_ = 'item birthday').find('strong').get_text()



来源:https://stackoverflow.com/questions/39069497/how-to-extract-the-strong-elements-which-are-in-div-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!