Python 2.7美丽汤图片源提取

20
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个回答

43

有一个更简单的解决方案:

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

2
五年过去了,这仍然是最优雅的。 - remykarem

31

你正在将beautifulsoup节点传递给re.findall函数,需要将它转换为字符串。尝试使用以下代码:

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

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

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

给出所有class为'sizedProdImage'的img标签的src属性列表。


0
在我的例子中,htmlText 包含 img 标签,但它也可以用于 URL。请参见我的答案这里
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']

0
你正在创建一个 re 对象,然后将其传递给 re.findall,而该函数期望第一个参数为字符串类型:
patImgSrc = re.compile('src="(.*)".*/>')
findPatImgSrc = re.findall(patImgSrc, imgsrc)

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

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

仍然出现错误: Traceback (most recent call last): File "C:\Users\BuyzDirect\Desktop\OverStock_Listing_Format_Tool.py", line 50, in <module> findPatImgSrc = patImgSrc.findall(imgsrc) TypeError: 预期字符串或缓冲区 - phales15

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接