简单的python爬虫程序

首先文章是看的别人的

https://www.cnblogs.com/xueweihan/p/4592212.html

相比较下,我的更简单些。

爬取的网站是http://bohaishibei.com/post/category/main/

过程的话,可以看上面那位作者写的过程。我在本文中就不一一赘述了。

下面直接上代码。记录自己的学习过程

import re
from urllib import request
root_pattern = '<article class="article-content">([\s\S]*?)</article>'
title_pattern= '】([\s\S]*?)</p>'
img_pattern='<p><img([\s\S]*?)<p>【'
img_pattern_src='src="([\s\S]*?)" alt'
#获取文本内容
def Get_Content(url):
    r=request.urlopen(url)
    html_content=r.read()
    html_content=str(html_content,encoding='utf-8')
    html_content=re.findall(root_pattern,html_content)
    return html_content
#重新对已经得到的网页中的数据进行重新处理,去掉标签。
def refineImgs(imgs):
    imgs_refined=[]
    for img in imgs:
        if type(img)==str:
            refine_imgsrc=re.findall(img_pattern_src,img)
            imgs_refined.append(refine_imgsrc)
        else:
            imgs_refined.append(img)
    return imgs_refined
#得到网页中的图片和标题
def Get_title_img(html_content):
        titles_imgs=[]
        imgs=[]
        for title_img_content in html_content:
            title_content1=re.findall(title_pattern,title_img_content)
            title_img_content=re.findall(img_pattern,title_img_content)
            for x in title_img_content:  
                if len(x)>200:#len(x)>200是为了处理有的一个标题有多个图片的问题
                    title_img_content = re.findall(img_pattern_src,x)
                    imgs.append(title_img_content)
                    continue
                imgs.append(x)
            title_img={'title':title_content1,'img':refineImgs(imgs)}
            titles_imgs.append(title_img)
        return titles_imgs
#把得到的数据放到txt文件中
def data_out(title_img_content):
    with open("E:\\data.txt","w+",encoding='utf-8') as fo:
        for i in title_img_content[0]['img']:
            fo.write('\n'.join(i))
            fo.write('\n')
        for j in title_img_content[0]['title']:
            fo.write('\n')
            fo.write(''.join(j))
            
title_content=Get_Content("https://bh.sb/post/42305/")
title_img_content=Get_title_img(title_content)
data_out(title_img_content)

猜你喜欢

转载自blog.csdn.net/sinat_34774688/article/details/87914813
今日推荐