2016-10-05 16 views
0

私はウェブサイトの特定の部分だけを解析しようとしています。以下は私のコードです。もっと効率的にするためにとにかくありますか?ここで beautifulsoupでウェブを掻き集める

from bs4 import BeautifulSoup 
import requests 
import urllib.request 
import json 

soup = BeautifulSoup(requests.get("http://www.example.com").content, "html.parser") 

for d in soup.select("script[type=text/javascript]"): 
    print(d.text[2300:2600]) 

は私が必要なものを出力し

> dataLayer = [{ 
>  'page':'ProductPage', 
>  'OAM':'False', 
>  'storeNum':'075', 
>  'brand':'Seagate', 
>  'productPrice':'69.99', 
>  'SKU':'106674', 
>  'productID':'467336', 
>  'mpn':'ST2000DM006', 
>  'ean':'763649110218', 
>  'category':'Internal Hard Drives', 
>  'isMobile':'False' }]; 

答えて

0
それは他のページに変更することができます

- (私は他のページでそれをチェックしませんでした)

for d in soup.select("script[type=text/javascript]")[27].text.split('\n')[51:62]: 
    print(d.strip()) 

結果

'page':'ProductPage', 
'OAM':'False', 
'storeNum':'029', 
'brand':'Microsoft', 
'productPrice':'129.99', 
'SKU':'883785', 
'productID':'456088', 
'mpn':'QC7-00001', 
'ean':'889842010060', 
'category':'Tablet Accessories', 
'isMobile':'False' 

EDIT:他のバージョン:

text = soup.select("head script[type=text/javascript]")[-1].text 

start = text.find('dataLayer = [{') + len('dataLayer = [{') 
end = text.rfind('}];') 

rows = text[start:end].strip().split('\n') 

for d in rows: 
    print(d.strip()) 
+0

おかげで完璧に動作します。 – Burak

関連する問題