Python3でbs4を使用して、amazonで検索した製品の詳細を取得しています。私のコードは次のとおりです。
from bs4 import BeautifulSoup as BS
import requests
html = requests.get('http://www.amazon.in/s/ref=nb_sb_noss_2?url=search-
alias%3Daps&field-keywords=hp+monitors')
soup = BS(html.text , 'lxml')
#print(soup.prettify())
for i in soup.find_all('li') :
print(i.get('id'))
h2_tag = i.h2
print(h2_tag.get('data-attribute'))
print("_____")
このコードでは、h2タグのdata-attribute属性の値を取得していません。一方、liタグのid属性の値が出てきています。誰かが私がどこで間違っているのか教えてもらえますか。
ここで言ういくつかのこと:
なぜlxml
ここで使うの?html.parser
大丈夫なはずです。
data-attribute
タグを使用する必要はありません:を使用して h2 からテキストを取得できますh2.text
。
製品タイトルを収集するより簡単な方法<h2>
は、s-inline
クラス (製品タイトル)を持つすべてを直接反復することです。
from bs4 import BeautifulSoup
import requests
html = requests.get('http://www.amazon.in/s/ref=nb_sb_noss_2?url=search-alias%3Daps&field-keywords=hp+monitors')
soup = BeautifulSoup(html.content , 'html.parser')
for h2 in soup.find_all('h2', class_='s-inline'):
print(h2.text)
出力
HP 24ES 23.8-HP 24ES 23.8-inch THINNEST LED Monitor (Black)LED Monitor (Black)
HP 22es Display 54.6 cm, 21.5 Inch THINNEST IPS LED Backlit Monitor
HP 22KD 21.5-inch FULL HD LED Backlit Monitor (Black
HP 19KA 18.5-inch LED Backlit Monitor (Black)
HP 27es 27 Inches Display IPS LED Backlit Monitor (Full HD)
HP 21KD 20.7-inch FULL HD LED Backlit Monitor (Black)
LG 24MP88HV-S 24"IPS Slim LCD Monitor
Dell S Series S2415H 24-Inch Screen Full HD HDMI LED Monitor
Dell E1916HV 18.5-inch LED Monitor (Black)
HP 20KD 19.5-inch LED Backlit Monitor (Black)
Dell S2216H 21.5-Inch Full HD LED Monitor
HP V222 21.5" LED Widescreen Monitor (M1T37AA Black)
AlexVyan®-Genuine Accessory with 1 year warranty:= (38.1CM) 15 Inch LCD Monitor for HP, Dell, Lenovo, Pc Desktop Computer Only (Black)
Compaq B191 18.5-inch LED Backlit Monitor (Black)
HP 20WD 19.45-Inch LED Backlit Monitor
HP Compaq F191 G9F92AT 18.5-inch Monitor
また、インライン コードに太字を使用する代わりに、次のようなバッククォートを使用します。
`codecode` は次のようにレンダリングされます codecode
編集:
ここでsoup.find_all('h2')
は、ページからすべての h2 タグを取得しますが、amazon ページには製品以外の要素の h2 タグもあります。すべての製品にs-inline
クラスがあることに気付いたのでsoup.find_all('h2', class_='s-inline")
、製品から h2 タグのみを取得します。
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加