2011-11-27 15 views
14
for imgsrc in Soup.findAll('img', {'class': 'sizedProdImage'}): 
    if imgsrc: 
     imgsrc = imgsrc 
    else: 
     imgsrc = "ERROR" 

patImgSrc = re.compile('src="(.*)".*/>') 
findPatImgSrc = re.findall(patImgSrc, imgsrc) 

print findPatImgSrc 

''' 
<img height="72" name="proimg" id="image" class="sizedProdImage" src="http://imagelocation" /> 

Questo è quello che sto cercando di estrarre da e sto ottenendo:Python 2.7 Beautiful Soup img src Estratto

findimgsrcPat = re.findall(imgsrcPat, imgsrc) 
File "C:\Python27\lib\re.py", line 177, in findall 
    return _compile(pattern, flags).findall(string) 
TypeError: expected string or buffer 

'''

risposta

29

si sta passando nodo BeautifulSoup a re.findall. Devi convertirlo in stringa. Prova:

findPatImgSrc = re.findall(patImgSrc, str(imgsrc)) 

Meglio ancora, utilizzare gli strumenti BeautifulSoup dispone quanto segue:

[x['src'] for x in soup.findAll('img', {'class': 'sizedProdImage'})] 

fornisce un elenco di tutti gli attributi src di tag img di classe 'sizedProdImage'.

0

Stai creando un oggetto re, poi passando in re.findall che prevede una stringa come primo argomento:

patImgSrc = re.compile('src="(.*)".*/>') 
findPatImgSrc = re.findall(patImgSrc, imgsrc) 

Invece, utilizzare th e .findall metodo della patImgSrc voi oggetto appena creato:

patImgSrc = re.compile('src="(.*)".*/>') 
findPatImgSrc = patImgSrc.findall(imgsrc) 
+0

ancora ottenere l'errore: Traceback (chiamata più recente scorso): file "C: \ Users \ BuyzDirect \ Desktop \ OverStock_Listing_Format_Tool.py", linea 50, in findPatImgSrc = patImgSrc .findall (imgsrc) TypeError: stringa o buffer previsto – phales15

27

C'è più semplice soluzione:

soup.find('img')['src'] 
0

Nel mio esempio, il htmlText contiene il tag img, ma può essere utilizzato per un URL troppo. Vedere la mia risposta here

from BeautifulSoup import BeautifulSoup as BSHTML 
htmlText = """<img src="https://src1.com/" <img src="https://src2.com/" /> """ 
soup = BSHTML(htmlText) 
images = soup.findAll('img') 
for image in images: 
    print image['src'] 
Problemi correlati