Python 布尔表达式始终为真(当它不应该为真时)
我有一个方法,旨在从某些 html 中获取所有 img 元素,并添加 css 样式以确保图像较大时调整其大小。在最终测试之前它效果很好:largest_size < img_size - 我尝试了各种不同的方式来表达这个简单的事情,但它总是评估为 true - 这意味着所有图像都会调整大小,无论其原始大小如何。
代码:
def adjust_html(self, html_text):
# pull image links and adjust those larger than 30k
# to be width=100%
html = etree.HTML(html_text)
r = html.xpath('.//img')
changed_text = False
for elem in r:
for tag, value in elem.attrib.iteritems():
if tag == 'src':
largest_size = 30720
img_size = 0
img_url = value
if self.bad_urls.has_key(img_url):
break
try:
usock = urllib2.urlopen(img_url)
img_size = usock.info().get('Content-Length')
except:
self.log.debug("***** 406 for " + img_url)
self.bad_urls[img_url] = True
break
if img_size is None:
break
else:
**if (largest_size < img_size):**
self.log.debug("*** " + img_url + " ***")
self.log.debug("********** img size = " + str(img_size) + " **********")
elem.set("style","width:100%")
changed_text = True
break
if changed_text == True:
html_text = etree.tostring(html)
return html_text
我知道这里一定有一些简单的错误 - 我只是没有看到它:)
I have a method that is intended to grab all img elements from some html and to add a css style to ensure the image is resized if it is large. It works great until the final test : largest_size < img_size - I have tried all manner of different ways to express this simple thing, and yet it always evaluates to true - which means all images are resized regardless of their original size.
The code:
def adjust_html(self, html_text):
# pull image links and adjust those larger than 30k
# to be width=100%
html = etree.HTML(html_text)
r = html.xpath('.//img')
changed_text = False
for elem in r:
for tag, value in elem.attrib.iteritems():
if tag == 'src':
largest_size = 30720
img_size = 0
img_url = value
if self.bad_urls.has_key(img_url):
break
try:
usock = urllib2.urlopen(img_url)
img_size = usock.info().get('Content-Length')
except:
self.log.debug("***** 406 for " + img_url)
self.bad_urls[img_url] = True
break
if img_size is None:
break
else:
**if (largest_size < img_size):**
self.log.debug("*** " + img_url + " ***")
self.log.debug("********** img size = " + str(img_size) + " **********")
elem.set("style","width:100%")
changed_text = True
break
if changed_text == True:
html_text = etree.tostring(html)
return html_text
I know there has to be something simple wrong here - I just don't see it :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
int
始终小于str
。首先将标头值转换为int
。请记住,使用repr()
进行调试,而不是str()
。int
is always less thanstr
. Turn your header value into anint
first. And remember, debug withrepr()
, notstr()
.img_size 是一个字符串而不是整数:
img_size is a string not an int: