Python 2.7美丽的汤Img Src Extract

pha*_*s15 20 python beautifulsoup

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" />
Run Code Online (Sandbox Code Playgroud)

这就是我想从中提取的内容,我得到了:

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
Run Code Online (Sandbox Code Playgroud)

"""

Sta*_*eyD 41

有更简单的解决方案:

 soup.find('img')['src']
Run Code Online (Sandbox Code Playgroud)

  • 5年后,这仍然是最优雅的。 (2认同)

sou*_*eck 31

你将beautifulsoup节点传递给re.findall.你必须将它转换为字符串.尝试:

findPatImgSrc = re.findall(patImgSrc, str(imgsrc))
Run Code Online (Sandbox Code Playgroud)

更好的是,使用beautifulsoup提供的工具:

[x['src'] for x in soup.findAll('img', {'class': 'sizedProdImage'})]
Run Code Online (Sandbox Code Playgroud)

给出了类'sizedProdImage'的img标签的所有src属性的列表.