Python 2.7 提取 Beautiful Soup 中的 Img Src

20 投票
4 回答
37415 浏览
提问于 2025-04-17 07:11
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" />
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

这是我想要提取的内容,而我得到的是:

'''

4 个回答

0

你正在创建一个 re 对象,然后把它传给 re.findall,这个方法需要第一个参数是一个字符串:

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

相反,你应该使用刚刚创建的 patImgSrc 对象的 .findall 方法:

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

这里有一个更简单的解决办法:

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

你把beautifulsoup的节点传给了re.findall。你需要先把它转换成字符串。试试这个:

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

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

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

这样可以得到所有类名为'sizedProdImage'的img标签的src属性的列表。

撰写回答