python 질문드립니다.

매출이 오르면 내리는 수수료! 지금 수수료센터에서 전자결제(PG)수수료 비교견적 신청해 보세요!
python 질문드립니다.

QA

python 질문드립니다.

본문

안녕하세요.

python 으로 특정 위치에 있는 값만 가져오고 싶은데

어떻게 가져와야할지 모르겠네요

255, 199, 201 값만 find나 select_one함수로 가져오고 싶습니다.

감사합니다.

 

<div class="section_toon_info " style="background-color: rgb(255, 199, 201); touch-action: pan-y; user-select: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);">

 

print (soup.head.find("section_toon_info", {"background-color":"rgb"}))

 

이 질문에 댓글 쓰기 :

답변 3

안녕하세요.

아래의 코드를 참고해 보시겠어요~

 


import re
from bs4 import BeautifulSoup
html_doc = """
<div class="section_toon_info " style="background-color: rgb(255, 199, 201); touch-action: pan-y; user-select: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# 'style' 속성을 가진 모든 요소를 찾습니다.
elements = soup.select('[style]')
# 필요한 값을 가진 요소를 필터링합니다.
filtered_elements = []
for el in elements:
    style_string = el['style']
    match = re.search(r'background-color: rgb\((\d+), (\d+), (\d+)\)', style_string)
    if match:
        rgb_values = match.groups()  # RGB 값을 추출합니다.
        if rgb_values:
            filtered_elements.append((el, rgb_values))  # 요소와 함께 RGB 값을 저장합니다.
# 필터링된 요소들과 RGB 값을 출력합니다.
for el, rgb in filtered_elements:
    print(f'Element: {el}, RGB: {rgb}')

안녕하세요.

아래의 코드를 참고를 해보시겠어요?

 


from bs4 import BeautifulSoup
html_doc = """
<div class="section_toon_info " style="background-color: rgb(255, 199, 201); touch-action: pan-y; user-select: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
"""
soup = BeautifulSoup(html_doc, 'html.parser')
# 'style' 속성을 가진 모든 요소를 찾습니다.
elements = soup.select('[style]')
# 필요한 값을 가진 요소를 필터링합니다.
filtered_elements = [el for el in elements if 'background-color: rgb(255, 199, 201)' in el['style']]
# 필터링된 요소들을 출력합니다.
for el in filtered_elements:
    print(el)

 

아직 해결이 되지 않으셨다면 다음을 참고하셔서 적용해 보시는건 어떨까요?

 


from bs4 import BeautifulSoup
html = '''
<div class="section_toon_info" style="background-color: rgb(255, 199, 201); touch-action: pan-y; user-select: none; -webkit-user-drag: none; -webkit-tap-highlight-color: rgba(0, 0, 0, 0);">
    <!-- Your content here -->
</div>
'''
# BeautifulSoup 객체 생성
soup = BeautifulSoup(html, 'html.parser')
# 클래스 이름으로 요소 찾기
toon_info_div = soup.find("div", class_="section_toon_info")
# style 속성에서 배경색 추출
style_attribute = toon_info_div.get('style', '')
# 배경색 추출
background_color_start = style_attribute.find("rgb(")
background_color_end = style_attribute.find(")", background_color_start + 1)
background_color = style_attribute[background_color_start + 4:background_color_end]
# RGB 값을 리스트로 변환
rgb_values = list(map(int, background_color.split(',')))
print(rgb_values)

 

이렇게 하면 해당 div 요소를 찾고, 그 요소의 style 속성에서 배경색을 추출한 후에 RGB 값을 리스트로 변환하여 출력하게 되며, 이때, find 함수 대신 find_all을 사용하면 여러 개의 해당 요소를 찾을 수 있게 됩니다. 필요에 따라 코드를 수정하여 적절히 활용하시면 되지 않을까 합니다.

답변을 작성하시기 전에 로그인 해주세요.
전체 104
QA 내용 검색

회원로그인

(주)에스아이알소프트 / 대표:홍석명 / (06211) 서울특별시 강남구 역삼동 707-34 한신인터밸리24 서관 1404호 / E-Mail: admin@sir.kr
사업자등록번호: 217-81-36347 / 통신판매업신고번호:2014-서울강남-02098호 / 개인정보보호책임자:김민섭(minsup@sir.kr)
© SIRSOFT