2017-02-11 30 views
2

beautifulsoupのselectメソッドに複数の引数を指定する方法はありますか?beautifulsoupのCSSセレクタで複数のタグを取得する

soup.select('div[class^="TypeA"]'でデータを取得しています。これは、クラスがパターンTypeAと一致するすべてのdivを私に取得します。私はまた、別のdivを取得することに興味がありますclass="TypeB"(完全一致)。

今私はおそらく2つの別々のパスでこれを行うことができます。次のように入力します。

r = requests.get(jurl) 
soup = BeautifulSoup(r.text,"lxml") 
list1 = [] 
#get typeA divs 
for div in soup.select('div[class^="TypeA"]'): 
    t = [text for text in div.stripped_strings] 
    list1.append(t) 
list2 = [] 
#get typeB divs 
for div in soup.select('div[class^="TypeB"]'): 
    t = [text for text in div.stripped_strings] 
    list2.append(t) 
#combine the two into tuples. Both lists are of the same size 
list3 = [] 
count = 0 
for item in list1: 
    list3.append((item,list2[count])) 
    count += 1  
print list3 

ただし、1回のパスで行うことはできますか? documentationを見ると、これがどうやってできるのかはすぐに分かりません。

+0

を使用するために、ジッパーでDIV2(soup.select( 'divの[クラス^ = "TypeA"] ')、soup.select(' div [クラス^ = "TypeB"] ')): ' – Arman

答えて

2
soup.select('div[class^="TypeA"], div[class^="TypeB"]') 

使用,あなたはDIV1のために `zip`機能を`使用することができ、複数のセレクタ

CSS Selector Reference

enter image description here

+0

これはなんですか?なぜ二つの 'typeA'クラス? – Arman

+0

ありがとうもう一度宏杰李! –

関連する問題