在获取网站真是图片的时候,经常遇到图片链接残缺问题。

例如下图所示的情况:

img标签中的图片链接是残缺的,如果这个网站域名又是多种情况的话,比如

  http://sports.online.sh.cn/content/2018-03/13/content_8813151.htm

  http://sports.online.sh.cn/images/attachement/jpg/site1/20180313/IMG4ccc6a76b0f047094677984.JPG

  http://shenhua.online.sh.cn/content/2018-03/13/content_8813187.htm

  http://shenhua.online.sh.cn/images/attachement/jpg/site1/20180313/IMGd43d7e5f35354709509383.JPG

这两条新闻是同一个网站的,但是不同的新闻页面,图片的链接又是残缺的,如何获取真正的图片链接呢?

首先,我们需要判断当前页的域名。将鼠标移至图片残缺url上面就会看到完整的url链接。一般残缺图片链接的缺失部分,正是网址栏中的域名部分。

之后,我们就可以在代码中进行判断,如:

    def parse_item(self, response, spider):
self.item = self.load_item(response)
if 'sports' in response.url:
self.item['content'] = self.item['content'].replace('../../../images', 'http://sports.online.sh.cn/images')
elif 'shenhua' in response.url:
self.item['content'] = self.item['content'].replace('../../../images', 'http://shenhua.online.sh.cn/images')
yield self.item

~上面使用成员操作符 in来查找相应的域名,是较为实用简单的判断方法,相同的做用判断还可以用以下几种方法来实现:

~使用string模块的index()/rindex()方法 
index()/rindex()方法跟find()/rfind()方法一样,只不过找不到子字符串的时候会报一个ValueError异常。

import string

def find_string(s,t):
try:
string.index(s,t)
return True
except(ValueError):
return False s='nihao,shijie'
t='nihao'
result = find_string(s,t)
print result #True

~使用字符串对象的find()/rfind()、index()/rindex()和count()方法

>>> s='nihao,shijie'
>>> t='nihao'
>>> result = s.find(t)>=0
>>> print result
True
>>> result=s.count(t)>0
>>> print result
True
>>> result=s.index(t)>=0
>>> print result
True

最新文章

  1. 第3月第21天 nsclassfromstring返回null SVN报错:clean the working copy and then retry the operation
  2. 对象关系映射ORM
  3. 无法解析此远程名称: 'www.***.com' 解决办法 请求因 HTTP 状态 417 失败
  4. 使用C++还是QML
  5. .NET中开源CMS目录
  6. iOS 使用GBK编码的hmacMD5算法
  7. 转载自前端开发:CSS设置滚动条样式
  8. 微信小程序 网络请求之re.request 和那些坑
  9. MyBatis3入门
  10. Java初学习-常见单词
  11. Spark1.6之后为何使用Netty通信框架替代Akka
  12. [luogu2149][bzoj1880][SDOI2009]Elaxia的路线【拓扑排序+最短路+DP】
  13. 隐藏SharePoint 2013 team sites里的follow按钮
  14. 关于ARMv8另外几个问题
  15. weblogic查看版本号教程
  16. 给MySQL增加一个表示例
  17. 折腾到死:matlab7.0 安装
  18. andriod 下一个页面
  19. java 并发——理解 wait / notify / notifyAll
  20. vscode设置中文,设置中文不成功问题

热门文章

  1. java.lang.NumberFormatException
  2. Alice and Bob HDU - 4268
  3. JNDI在本项目中的应用
  4. Python基础__Python序列基本类型及其操作(1)
  5. 简述Spring事务有几种管理方法,写出一种配置方式
  6. spring中aop的注解实现方式简单实例
  7. struts_自定义日期类型转换器
  8. js备战春招の四のdevtool中各种错误、调试的使用技巧
  9. Problem : 1196 ( Lowest Bit )
  10. Firefox配置文件夹详解