【问题标题】:Missing values while scraping using beautifulsoup in python在python中使用beautifulsoup进行抓取时缺少值
【发布时间】:2020-10-10 17:17:33
【问题描述】:

我正在尝试将网络抓取作为我使用 python 的第一个项目(对编程来说是全新的),我几乎完成了,但是网页上的一些值丢失了,所以我想用一些东西替换那个缺失的值比如“0”或“未找到”,其实我只是想从数据中制作一个 csv 文件,而不是真正进行分析。

我正在抓取的网页是:https://www.lamudi.com.mx/nuevo-leon/departamento/for-rent/?page=1

我有一个循环,它收集页面的所有链接,然后转到每个链接以抓取数据并将其保存在列表中,但是我的某些列表的元素比其他列表少。所以我只想让我的程序识别何时是缺失值,并将“0”或“未找到”附加到我的“尺寸”列表中。

用于收集页面上的链接:

tags = soup('a',{'class':'js-listing-link'})
for tag in tags:
    link = tag.get('href')
    if link not in links:
        links.append(link)

print("Number of Links:", len(links))

对于收集每个部门的大小:

for link in links:
    size = soup('span',{'class':'Overview-attribute icon-livingsize-v4'})
    for mysize in size:
        mysize = mysize.get_text().strip()
        sizes.append(mysize)

print("Number of Sizes:", len(sizes))

【问题讨论】:

    标签: python html web-scraping beautifulsoup missing-data


    【解决方案1】:

    在此页面上,您可以选择所有列表行(使用.select('.ListingCell-row')),然后选择其中的所有信息(并用- 替换缺少的信息):

    import requests
    from bs4 import BeautifulSoup
    
    
    url = 'https://www.lamudi.com.mx/nuevo-leon/departamento/for-rent/?page=1'
    headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:81.0) Gecko/20100101 Firefox/81.0'}
    soup = BeautifulSoup(requests.get(url, headers=headers).content, 'html.parser')
    
    for row in soup.select('.ListingCell-row'):
        name = row.h3.get_text(strip=True)
        link = row.h3.a['href']
        size = row.select_one('.icon-livingsize')
        size = size.get_text(strip=True) if size else '-'
        print(name)
        print(link)
        print(size)
        print('-' * 80)
    

    打印:

    Loft en Renta Amueblado Una Recámara Cerca Udem
    https://www.lamudi.com.mx/loft-en-renta-amueblado-una-recamara-cerca-udem.html
    50 m²
    --------------------------------------------------------------------------------
    DEPARTAMENTO EN RENTA SAN JERONIMO EQUIPADO
    https://www.lamudi.com.mx/departamento-en-renta-san-jeronimo-equipado.html
    -
    --------------------------------------------------------------------------------
    Departamento - Narvarte
    https://www.lamudi.com.mx/departamento-narvarte-58.html
    60 m²
    --------------------------------------------------------------------------------
    
    ...and so on.
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-13
      • 1970-01-01
      • 2019-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多