Need to create a dictionary of two span tags with in a wrapped up in a container. Using beautiful soups

∥☆過路亽.° 提交于 2021-01-28 19:37:32

问题


I am scrapping some listings of a website and managed to get most of the features to work except scrapping the description.

here is the URL of one ad : https://eg.hatla2ee.com/en/car/honda/civic/3289785

Here is my code:

for link in df['New Carlist Unit 1_link']:
    url = requests.get(link)
    soup  = BeautifulSoup(url.text, 'html.parser')
    ### Get title 
    title =[]
    try:
        title.append(soup.find('h1').text.strip())
    except Exception as e:
        None


    ## Get price
    price = []
    try:
        price.append(soup.find('span',class_="usedUnitCarPrice").text.strip())
    except Exception as e:
        None

    ##Get Description box

    label =[]
    text =[]
    try:
        for span in soup.find_all('span',class_="DescDataSubTit"):
            label.append(span.text.strip())
            text.append(span.find_next_sibling().text.strip())


    except Exception as e:
        None
    print('*'*100)
    print(title)
    print(price)
    print(label)
    print(text)
    time.sleep(1)

I cant seem to collect all the span tags for some reason.

Here is the output I want:

{'Make': 'Honda'}
{'Model': 'Crosstour'}
{'Used since': '2012'}
{'Km': '0 Km'}
{'Transmission': 'automatic'}
{'City': 'Cairo'}
{'Color': 'Gold'}
{'Fuel': 'gas'}

回答1:


import requests
from bs4 import BeautifulSoup


def main(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')
    target = soup.select_one("div.DescDataRow").select("span.DescDataSubTit")
    for tar in target:
        g = {tar.text: tar.find_next("span").get_text(strip=True)}
        print(g)


main("https://eg.hatla2ee.com/en/car/honda/civic/3289785")

Output:

{'Make': 'Honda'}
{'Model': 'Civic'}
{'Used since': '1990'}
{'Km': '1,500 Km'}
{'Transmission': 'automatic'}
{'City': 'Port Said'}
{'Color': 'Dark red'}
{'Fuel': 'gas'}
import requests
from bs4 import BeautifulSoup


def main(url):
    r = requests.get(url)
    soup = BeautifulSoup(r.content, 'html.parser')
    target = [list(item.stripped_strings)
              for item in soup.select("div.DescDataContain")][0][:16]
    print(dict(zip(*[iter(target)]*2)))


main("https://eg.hatla2ee.com/en/car/honda/civic/3289785")

Output:

{'Make': 'Honda', 'Model': 'Civic', 'Used since': '1990', 'Km': '1,500 Km', 'Transmission': 'automatic', 'City': 'Port Said', 'Color': 'Dark red', 'Fuel': 'gas'}


来源:https://stackoverflow.com/questions/61591843/need-to-create-a-dictionary-of-two-span-tags-with-in-a-wrapped-up-in-a-container

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