BeautifulSoup在csv中使用“ NA”填充缺少的信息

时间:2018-11-28 19:14:36

标签: python csv parsing beautifulsoup

我正在研究一个Web刮板,该刮板在Sigma-Aldrich网站上创建了所有化学品的.csv文件。 .csv文件将具有化学名称,后跟变量,例如产品编号,cas号,分子量和化学式。每行1个化学品+信息。

我遇到的问题是,并非所有化学品都具有其所有领域,许多化学品仅具有产品和CAS号。这导致我的.csv文件发生偏移,并且化学品行中的信息与其他化学品有关。

要纠正此错误,如果该字段为空,我想添加“ N / A”。

这是我的抓取方法:

def scraap(urlLi):
    for url in urlLi:
        content = requests.get(url).content
        soup = BeautifulSoup(content, 'lxml')
        containers = soup.find_all('div', {'class': 'productContainer-inner'})


        for c in containers:
            sub = c.find_all('div', {'class': 'productContainer-inner-content'})
            names = c.find_all('div', {'class': 'searchResultSubstanceBlock clearfix'})

            for n in names:
                hope = n.find("h2").text
                print(hope)
                nombres.append(hope.encode('utf-8'))

            for s in sub:
                info = s.find_all('ul', {'class': 'nonSynonymProperties'})
                proNum = s.find_all('div', {'class': 'product-listing-outer'})

                for p in proNum:
                    ping = p.find_all('div', {'class': 'row clearfix'})

                    for po in ping:
                        pro = p.find_all('li', {'class': 'productNumberValue'})
                        pnPp = []
                        for pri in pro:
                            potus = pri.get_text()
                            pnPp.append(potus.encode('utf-8'))

                    ProductNumber.append(pnPp)
                    print(pnPp)

                for i in info:
                    c = 1
                    for gling in i:
                        print(gling.get_text())
                        if c == 1:
                            formu.append(gling.get_text().encode('utf-8'))
                        elif c == 2:
                            molWei.append(gling.get_text().encode('utf-8'))
                        else:
                            casNum.append(gling.get_text().encode('utf-8'))

                        c += 1
                    c == 1
                    print("---")

这是我的写作方法:

def pipeUp():

    with open('sigma_pipe_out.csv', mode='wb') as csv_file:
        fieldnames = ['chem_name', 'productNum', 'formula', 'molWei', 'casNum']
        writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
        # writer.writeheader()
        # csv_file.write(' '.join(fieldnames))
        for n, p, f, w, c in zip(nombres, ProductNumber, formu, molWei, casNum):
            # writer.writerow([n, p, f, w, c])
            writer.writerow({'chem_name': n, 'productNum': p, 'formula': f, 'molWei': w, 'casNum': c})

问题出现在“从信息获取我:”部分。公式,molWei和casNum列表已关闭。

如果formu和molWei缺少信息,如何添加“ N / a”?

2 个答案:

答案 0 :(得分:0)

如果没有关于分子式和分子量的信息,我假设get_text()返回一个空字符串。在这种情况下,您可以添加:

if not molWei: molWei = "N/A"

如果字符串为空,则将molWei更新为N / A。

答案 1 :(得分:0)

您不能将索引用作值检查(if c == 1:),不能在添加到列表之前使用字符串检查

替换:

for i in info:
    ....
    ....
print("---")

具有:

rowNames = ['formu', 'molWei', 'casNum']

for li in info[0].find_all('li'):
    textVal = li.text.encode('utf-8')
    #print(textVal)
    if b'Formula' in textVal:
        formu.append(textVal)
        rowNames.remove('formu')
    elif b'Molecular' in textVal:
        molWei.append(textVal)
        rowNames.remove('molWei')
    else:
        casNum.append(textVal)
        rowNames.remove('casNum')

# add missing row here
if len(rowNames) > 1:
    for item in rowNames:
        globals()[item].append('NA')
print("---")
相关问题