전체 div 대신 BeautifulSoup에서 숫자 만 가져 오기
Nov 24 2020
BS4를 사용할 때만 숫자를 얻는 데 문제가 있지만 삶을 더 쉽게 만들기 위해 작은 웹 스크랩 프로그램을 만들어 파이썬을 배우려고합니다. 실제 광고를 스크랩 할 때 가격을 알 수 있었지만 페이지에서 모든 가격을 얻고 싶습니다.
내 코드는 다음과 같습니다.
from bs4 import BeautifulSoup
import requests
prices = []
url = 'https://www.kijiji.ca/b-cars-trucks/calgary/new__used/c174l1700199a49?ll=51.044733%2C-114.071883&address=Calgary%2C+AB&radius=50.0'
result = requests.get(url)
print (result.status_code)
src = result.content
soup = BeautifulSoup(src, 'html.parser')
print ("CLEARING")
price = soup.findAll("div", class_="price")
prices.append(price)
print (prices)
다음은 내 결과입니다.
[<div class="price">
$46,999.00 <div class="dealer-logo"> <div class="dealer-logo-image"> <img src="https://i.ebayimg.com/00/s/NjBYMTIw/z/xMQAAOSwi9ZfoW7r/$_69.PNG"/>
</div>
</div>
</div>
이상적으로는 출력이 "46,999.00"이되기를 원합니다.
text = True로 시도했지만 이것이 작동하지 않았고 빈 목록 외에는 출력을 얻지 못했습니다.
감사합니다
답변
1 MendelG Nov 24 2020 at 22:54
RegEx를 사용하지 않는 옵션 startwith()
은 달러 기호 가 있는 태그를 필터링하는 것입니다 $
.
import requests
from bs4 import BeautifulSoup
URL = 'https://www.kijiji.ca/b-cars-trucks/calgary/new__used/c174l1700199a49?ll=51.044733%2C-114.071883&address=Calgary%2C+AB&radius=50.0'
soup = BeautifulSoup(requests.get(URL).content, "html.parser")
price_tags = soup.find_all("div", class_="price")
prices = [
tag.get_text(strip=True)[1:] for tag in price_tags
if tag.get_text(strip=True).startswith('$')
]
print(prices)
산출:
['48,888.00', '21,999.00', '44,488.00', '5,500.00', '33,000.00', '14,900.00', '1,750.00', '35,600.00', '1,800.00', '25,888.00', '36,888.00', '32,888.00', '30,888.00', '18,888.00', '21,888.00', '29,888.00', '22,888.00', '30,888.00', '17,888.00', '17,888.00', '16,888.00', '22,888.00', '22,888.00', '34,888.00', '31,888.00', '32,888.00', '30,888.00', '21,888.00', '15,888.00', '21,888.00', '28,888.00', '19,888.00', '18,888.00', '30,995.00', '30,995.00', '30,995.00', '19,888.00', '47,995.00', '21,888.00', '46,995.00', '32,888.00', '29,888.00', '26,888.00', '21,888.00']
3 ATIFADIB Nov 24 2020 at 13:14
태그의 텍스트 부분을 가져온 다음 일부 정규식 처리를 수행해야합니다.
import re
def get_price_from_div(div_item):
str_price = re.sub('[^0-9\.]','', div_item.text)
float_price = float(str_price)
return float_price
div를 찾은 후 코드에서이 메서드를 호출하면됩니다.
from bs4 import BeautifulSoup
import requests
prices = []
url = 'https://www.kijiji.ca/b-cars-trucks/calgary/new__used/c174l1700199a49?ll=51.044733%2C-114.071883&address=Calgary%2C+AB&radius=50.0'
result = requests.get(url)
print (result.status_code)
src = result.content
soup = BeautifulSoup(src, 'html.parser')
print ("CLEARING")
price = soup.findAll("div", class_="price")
prices.extend([get_price_from_div(curr_div) for curr_div in price])
print (prices)