2013-04-22 5 views
0

Я разбираю html со следующего веб-сайта: http://www.asusparts.eu/partfinder/Asus/All В One/E Series Мне просто интересно, есть ли способ, которым я мог бы изучить анализируемый атрибут в python? Например .. Приведенный ниже код выводит следующее:Изучение атрибута в Python

datas = s.find(id='accordion') 

    a = datas.findAll('a') 

    for data in a: 

      if(data.has_attr('onclick')): 
       model_info.append(data['onclick']) 
       print data 

[ВЫХОД]

<a href="#Bracket" onclick="getProductsBasedOnCategoryID('Asus','Bracket','ET10B','7138', this, 'E Series')">Bracket</a> 

Эти значения Я хотел бы получить:

nCategoryID = Bracket 

nModelID = ET10B 

family = E Series 

Как страница выводится из AJAX. Они используют источник сценария, приводящий к следующему URL-адресу из файла сценария:

url = 'http://json.zandparts.com/api/category/GetCategories/' + country + '/' + currency + '/' + nModelID + '/' + family + '/' + nCategoryID + '/' + brandName + '/' + null 

Как я могу получить только 3 значения, перечисленные выше?


[EDIT]


import string, urllib2, urlparse, csv, sys 
from urllib import quote 
from urlparse import urljoin 
from bs4 import BeautifulSoup 
from ast import literal_eval 

changable_url = 'http://www.asusparts.eu/partfinder/Asus/All%20In%20One/E%20Series' 
page = urllib2.urlopen(changable_url) 
base_url = 'http://www.asusparts.eu' 
soup = BeautifulSoup(page) 

#Array to hold all options 
redirects = [] 
#Array to hold all data 
model_info = [] 

print "FETCHING OPTIONS" 
select = soup.find(id='myselectListModel') 
#print select.get_text() 


options = select.findAll('option') 

for option in options: 
    if(option.has_attr('redirectvalue')): 
     redirects.append(option['redirectvalue']) 

for r in redirects: 
    rpage = urllib2.urlopen(urljoin(base_url, quote(r))) 
    s = BeautifulSoup(rpage) 
    #print s 



    print "FETCHING MAIN TITLE" 
    #Finding all the headings for each specific Model 
    maintitle = s.find(id='puffBreadCrumbs') 
    print maintitle.get_text() 

    #Find entire HTML container holding all data, rendered by AJAX 
    datas = s.find(id='accordion') 

    #Find all 'a' tags inside data container 
    a = datas.findAll('a') 

    #Find all 'span' tags inside data container 
    content = datas.findAll('span') 

    print "FETCHING CATEGORY" 

    #Find all 'a' tags which have an attribute of 'onclick' Error:(doesn't display anything, can't seem to find 
    #'onclick' attr 
    if(hasattr(a, 'onclick')): 
     arguments = literal_eval('(' + a['onclick'].replace(', this', '').split('(', 1)[1]) 
     model_info.append(arguments) 
     print arguments #arguments[1] + " " + arguments[3] + " " + arguments[4] 


    print "FETCHING DATA" 
    for complete in content: 
     #Find all 'class' attributes inside 'span' tags 
     if(complete.has_attr('class')): 
      model_info.append(complete['class']) 

      print complete.get_text() 

    #Find all 'table data cells' inside table held in data container  
    print "FETCHING IMAGES" 
    img = s.find('td') 

    #Find all 'img' tags held inside these 'td' cells and print out 
    images = img.findAll('img') 
    print images 

Я добавил строку ошибки, где проблема укладывает ...

ответ

1

Вы могли бы parse that as a Python literal, если удалить this, части из это, и только взять все между скобками:

from ast import literal_eval 

if data.has_attr('onclick'): 
    arguments = literal_eval('(' + data['onclick'].replace(', this', '').split('(', 1)[1]) 
    model_info.append(arguments) 
    print arguments 

Мы удаляем аргумент this, потому что это не допустимый литерал строки python, и вы все равно не хотите его использовать.

Демо:

>>> literal_eval('(' + "getProductsBasedOnCategoryID('Asus','Bracket','ET10B','7138', this, 'E Series')".replace(', this', '').split('(', 1)[1]) 
('Asus', 'Bracket', 'ET10B', '7138', 'E Series') 

Теперь у вас есть Python кортеж и может выбрать любое значение, которое вы любите.

Вы хотите, чтобы значения с индексами 1, 2 и 4, например:

nCategoryID, nModelID, family = arguments[1], arguments[3], arguments[4] 
+0

Пожалуйста, посмотрите на мой отредактированный код .. – ash

+0

вы еще только печать 'data', не то, что извлеченный из' onclick' атрибута. –

+0

Вместо этого напечатайте 'arguments'; возвращаемое значение 'literal_eval'. –

1

Подобного ответом Мартейна, но делает примитивное использование pyparsing (то есть, она может быть уточнена распознавать функцию и только взять строки в кавычках с круглыми скобками):

from bs4 import BeautifulSoup 
from pyparsing import QuotedString 
from itertools import chain 

s = '''<a href="#Bracket" onclick="getProductsBasedOnCategoryID('Asus','Bracket','ET10B','7138', this, 'E Series')">Bracket</a>''' 
soup = BeautifulSoup(s) 
for a in soup('a', onclick=True): 
    print list(chain.from_iterable(QuotedString("'", unquoteResults=True).searchString(a['onclick']))) 
# ['Asus', 'Bracket', 'ET10B', '7138', 'E Series'] 
Смежные вопросы