爬网站文字链接及标题

任务:还是那个壁纸网站(就是之前这个啦https://blog.csdn.net/qq_40024605/article/details/79067580),这次要爬壁纸的文字标题及链接并写入文件保存

实现:

# -*- coding: utf-8 -*
import urllib
import re
#这个很重要,是能够让导入文件的文字能以中文形式保存,
具体可以参考这儿http://blog.csdn.net/crazyhacking/article/details/39375535
import sys
reload(sys)
sys.setdefaultencoding( "utf-8" )
f = open("3.txt", "a+")

def getHtml(url):
    page=urllib.urlopen(url)
    html=page.read()
    return html

def getTitle(html):
    reg =r'<div class="il_img"><a href="(.+?)" title="(.+?)" target="_blank"><img '#正则匹配
    imgre =re.compile(reg)
    list=re.findall(imgre,html)
    for p in list:
        print  """http://www.ivsky/.com"""+p[0],p[1]
        s=p[1]
        s=s.decode('utf-8')
        f.write("""http://www.ivsky/.com"""+p[0] +','+s+'\n')#写入文件


i=1
for i in range(1, 5):#循环,遍历url
    x=17*i
    html=getHtml("http://www.ivsky.com/bizhi/index_%s.html"%i)
    getTitle(html)
f.close()


 

猜你喜欢

转载自blog.csdn.net/qq_40024605/article/details/79067731