python double for loop attrs问题

时间:2018-12-11 22:34:25

标签: python for-loop beautifulsoup

所以我有以下两个BeautifulSoup发现和正在网页抓取的网页:

r = requests.get("https://www.viperprint.pl/produkt/arkusze-plano/AP01")
soup = BeautifulSoup(r.content)
elems = soup.find_all('a', {'class': 'tabela_cenowa eprint_product_link add_to_cart_link'})
hehes = soup.find_all('a', {'id': 'dLabel'})

我需要的是double for循环,该循环将列表打印到.csv文件中的单独列中。

这是我的问题:

>>> for elem, hehe in zip(elems, hehes):
...     nazwa = hehe.get('title')
...     qty = elem.attrs.get('data-qty')
...     print(nazwa, qty)

请给我下面的输出。这是错误的,因为第1列中的每个元素(因此,“ Arkusze PLANO”和所有波纹管)都应彼此相邻,并且第2列中的第一个数字(“ 100”)也应排成一行。

错误的输出:

('Arkusze PLANO', '100')

('A1+ (880 x 630 mm)', '250')

('Dwustronnie kolorowe (4+4 CMYK)', '500')

(u'Kreda b\u0142ysk 130g', '1000')

('Bez uszlachetniania (0+0)', '1500')

(None, '2000')

预期输出:

'Arkusze PLANO';'A1+ 880 x 630 mm';'Dwustronnie kolorowe 4+4 CMYK';u'Kreda b\u0142ysk 130g';'Bez uszlachetniania 0+0';'100'

我想做的是使用.attrs函数,如下所示:

for elem, hehe in zip(elems, hehes):
    nazwa = hehe[0].get('title')
    format = hehe[1].get('title')
    qty = elem.attrs.get('data-qty')
    print(nazwa, format, qty)

...但是我遇到了以下错误,并且不知道如何继续:

Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/usr/lib/python2.7/site-packages/bs4/element.py", line 905, in __getitem__
return self.attrs[key]
KeyError: 0

对于这么长的帖子,我感到抱歉,但是我想提供尽可能多的细节。

2 个答案:

答案 0 :(得分:0)

这将为您提供所需的列表中输出:

import requests
import bs4


r = requests.get("https://www.viperprint.pl/produkt/arkusze-plano/AP01")
soup = bs4.BeautifulSoup(r.content, 'html.parser')
elems = soup.find_all('a', {'class': 'tabela_cenowa eprint_product_link add_to_cart_link'})
hehes = soup.find_all('a', {'id': 'dLabel'})

results = []

nazwa_list = []
qty_value = None

for elem, hehe in zip(elems, hehes):
    nazwa = hehe.get('title')

    if qty_value == None:
        qty_value = elem.attrs.get('data-qty')

    if nazwa != None:
        nazwa_list.append(nazwa)

nazwa_list.append(qty_value)
results = nazwa_list

输出:

In  [1]: print (results)
Out [1]: ['Arkusze PLANO', 'A1+ (880 x 630 mm)', 'Dwustronnie kolorowe (4+4 CMYK)', 'Kreda błysk 130g', 'Bez uszlachetniania (0+0)', '100']

但是您声明要放入csv。因此,您可以将其放入表格中,然后根据需要使用它

import requests
import bs4
import pandas as pd

r = requests.get("https://www.viperprint.pl/produkt/arkusze-plano/AP01")
soup = bs4.BeautifulSoup(r.content, 'html.parser')
elems = soup.find_all('a', {'class': 'tabela_cenowa eprint_product_link add_to_cart_link'})
hehes = soup.find_all('a', {'id': 'dLabel'})


results = pd.DataFrame()

for elem, hehe in zip(elems, hehes):
    nazwa = hehe.get('title')
    qty = elem.attrs.get('data-qty')
    temp_df = pd.DataFrame([[nazwa, qty]], columns = ['title', 'qty'])

    results = results.append(temp_df)

答案 1 :(得分:0)

我添加了另一个循环以获得完全想要的输出。

for elem in elems:
    qty = elem.attrs.get('data-qty')
    print(results, qty, pricenum)

谢谢大家的帮助!