网站爬虫,主要是爬博客http://www.cnblogs.com/xxxx下的所有文章内容及标题,保存到data目录下。具体如下:
import requests import re import os BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATA_PATH = os.path.join(BASE_PATH, 'data') #将爬虫下来的文章内容写入文件,需要写入文章的内容、编码 def write_content(filename, content, coding): with open(os.path.join(DATA_PATH, filename), 'w', coding) as fw: fw.write(content) url = 'http://www.cnblogs.com/xxxx' def get_html(url): #打开url并获取该url的所有html信息 html_content = requests.get(url).text #从html_conten所有的html信息中匹配到所有博客的超链接地址 href_list = re.findall(r'href="(.*)">(.*)</a>', html_content) for line in href_list: line_html = requests.get(line[0]) content = line[1] # 获取每篇文章的标题titile line_content = line_html.text # 获取文章的内容 line_conding = line_html.encoding # 获取文章的编码格式 # 写入文件 write_content('%s.html' % content, line_content, line_conding) if __name__ == '__main__': get_html(url)
网站爬虫,爬取http://tieba.baidu.com/p/2166231880内所有的图片并保持到本地。
待续