原创python爬虫代码

主要用到urllib2、BeautifulSoup模块

#encoding=utf-8
import re
import requests
import urllib2
import datetime
import MySQLdb
from bs4 import BeautifulSoup
import sys
reload(sys)
sys.setdefaultencoding("utf-8") class Splider(object):
def __init__(self):
print u'开始爬取内容...' ##用来获取网页源代码
def getsource(self,url):
headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2652.0 Safari/537.36'}
req = urllib2.Request(url=url,headers=headers)
socket = urllib2.urlopen(req)
content = socket.read()
socket.close()
return content ##changepage用来生产不同页数的链接
def changepage(self,url,total_page):
now_page = int(re.search('page/(\d+)',url,re.S).group(1))
page_group = []
for i in range(now_page,total_page+1):
link = re.sub('page/(\d+)','page/%d' % i,url,re.S)
page_group.append(link)
return page_group #获取字内容
def getchildrencon(self,child_url):
conobj = {}
content = self.getsource(child_url)
soup = BeautifulSoup(content, 'html.parser', from_encoding='utf-8')
content = soup.find('div',{'class':'c-article_content'})
img = re.findall('src="(.*?)"',str(content),re.S)
conobj['con'] = content.get_text()
conobj['img'] = (';').join(img)
return conobj ##获取内容
def getcontent(self,html_doc):
soup = BeautifulSoup(html_doc, 'html.parser', from_encoding='utf-8')
tag = soup.find_all('div',{'class':'promo-feed-headline'})
info = {}
i = 0
for link in tag:
info[i] = {}
title_desc = link.find('h3')
info[i]['title'] = title_desc.get_text()
post_date = link.find('div',{'class':'post-date'})
pos_d = post_date['data-date'][0:10]
info[i]['content_time'] = pos_d
info[i]['source'] = 'whowhatwear'
source_link = link.find('a',href=re.compile(r"section=fashion-trends"))
source_url = 'http://www.whowhatwear.com'+source_link['href']
info[i]['source_url'] = source_url
in_content = self.getsource(source_url)
in_soup = BeautifulSoup(in_content, 'html.parser', from_encoding='utf-8')
soup_content = in_soup.find('section',{'class':'widgets-list-content'})
info[i]['content'] = soup_content.get_text().strip('\n')
text_con = in_soup.find('section',{'class':'text'})
summary = text_con.get_text().strip('\n') if text_con.text != None else NULL
info[i]['summary'] = summary[0:200]+'...';
img_list = re.findall('src="(.*?)"',str(soup_content),re.S)
info[i]['imgs'] = (';').join(img_list)
info[i]['create_time'] = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
i+=1
#print info
#exit()
return info def saveinfo(self,content_info):
conn = MySQLdb.Connect(host='127.0.0.1',user='root',passwd='',port=3306,db='test',charset='utf8')
cursor = conn.cursor()
for each in content_info:
for k,v in each.items():
sql = "insert into t_fashion_spider2(`title`,`summary`,`content`,`content_time`,`imgs`,`source`,`source_url`,`create_time`) values ('%s','%s','%s','%s','%s','%s','%s','%s')" % (MySQLdb.escape_string(v['title']),MySQLdb.escape_string(v['summary']),MySQLdb.escape_string(v['content']),v['content_time'],v['imgs'],v['source'],v['source_url'],v['create_time'])
cursor.execute(sql) conn.commit()
cursor.close()
conn.close() if __name__ == '__main__':
classinfo = []
p_num = 5
url = 'http://www.whowhatwear.com/section/fashion-trends/page/1'
jikesplider = Splider()
all_links = jikesplider.changepage(url,p_num)
for link in all_links:
print u'正在处理页面:' + link
html = jikesplider.getsource(link)
info = jikesplider.getcontent(html)
classinfo.append(info)
jikesplider.saveinfo(classinfo)

python爬虫代码的更多相关文章

  1. 动态调整线程数的python爬虫代码分享

    这几天在忙一个爬虫程序,一直在改进他,从一开始的单线程,好几秒一张图片(网络不好),,,到现在每秒钟十几张图片,,, 四个小时586万条数据,,,简直不要太爽 先上图 最终写出来的程序,线程数已经可以 ...

  2. 我不就是吃点肉,应该没事吧——爬取一座城市里的烤肉店数据(附完整Python爬虫代码)

    写在前面的一点屁话: 对于肉食主义者,吃肉简直幸福感爆棚!特别是烤肉,看着一块块肉慢慢变熟,听着烤盘上"滋滋"的声响,这种期待感是任何其他食物都无法带来的.如果说甜点是" ...

  3. 爬取汽车之家新闻图片的python爬虫代码

    import requestsfrom bs4 import BeautifulSouprespone=requests.get('https://www.autohome.com.cn/news/' ...

  4. 【图文详解】python爬虫实战——5分钟做个图片自动下载器

    python爬虫实战——图片自动下载器 之前介绍了那么多基本知识[Python爬虫]入门知识,(没看的先去看!!)大家也估计手痒了.想要实际做个小东西来看看,毕竟: talk is cheap sho ...

  5. 如何用Python爬虫实现百度图片自动下载?

    Github:https://github.com/nnngu/LearningNotes 制作爬虫的步骤 制作一个爬虫一般分以下几个步骤: 分析需求 分析网页源代码,配合开发者工具 编写正则表达式或 ...

  6. python爬虫实战——5分钟做个图片自动下载器

      python爬虫实战——图片自动下载器 制作爬虫的基本步骤 顺便通过这个小例子,可以掌握一些有关制作爬虫的基本的步骤. 一般来说,制作一个爬虫需要分以下几个步骤: 分析需求(对,需求分析非常重要, ...

  7. Python爬虫二

    常见的反爬手段和解决思路 1)明确反反爬的主要思路 反反爬的主要思路就是尽可能的去模拟浏览器,浏览器在如何操作,代码中就如何去实现;浏览器先请求了地址url1,保留了cookie在本地,之后请求地址u ...

  8. 利用python爬虫爬取图片并且制作马赛克拼图

    想在妹子生日送妹子一张用零食(或者食物类好看的图片)拼成的马赛克拼图,因此探索了一番= =. 首先需要一个软件来制作马赛克拼图,这里使用Foto-Mosaik-Edda(网上也有在线制作的网站,但是我 ...

  9. Python爬虫笔记技术篇

    目录 前言 requests出现中文乱码 使用代理 BeautifulSoup的使用 Selenium的使用 基础使用 Selenium获取网页动态数据赋值给BeautifulSoup Seleniu ...

随机推荐

  1. DNA Pairing

    function pair(str) { //return str; var arr = str.split(''); var pait = ''; var result = arr.map(func ...

  2. fail2ban 原理 安装 使用

    cd fail2ban python setup.py install /etc/fail2ban/ 为配置文件目录; /usr/lib/pythonx.x/site-packages/fail2ba ...

  3. 一个自己用的代码备份工具,支持delphi,android,java,可以自己添加配置,灵活支持大部分编程语言

    下面就是这个软件的下载地址 http://files.cnblogs.com/files/stevenlaz/release.zip 绿色软件 MConfig.exe 进行安装,或者卸载 MBacku ...

  4. 管道导致的while循环体变量失效

    #!/bin/sh num= cat /etc/passwd | while read line do num=$(($num+)) done echo $num linux:~ # sh a.sh ...

  5. js获取文件大小

    var file = urlBox.doc.activeElement.files[0]||urlBox.files[0] ; if (file) { var fileSize = 0; if (fi ...

  6. RHEL查看CPU等机器信息

    查看CPU信息: [root@pqsfc072 ~]# cat /proc/cpuinfo 查看CPU型号: [root@pqsfc072 ~]# cat /proc/cpuinfo | grep n ...

  7. QEMU/KVM功能测试

    最近在对QEMU/KVM在HP服务器进行功能测试,项目刚刚启动,遇到不少问题,从Git上拿到最新的source build进行测试,在RHEL7.0a3 + Kernel version3.10 + ...

  8. PHP ftp使用

    本文章来总结几个利用php中的ftp功能来实现通过FTP上传文件,有需要学习的朋友可参考参考.ftp_get() 函数从 FTP 服务器上下载一个文件.若成功则返回 true,失败则返回 false. ...

  9. CALayer图层的基本介绍

    掌握 ● CALayer的基本属性 ● CALayer和UIView的关系 ● position和anchorPoint的作⽤用 CALayer ● 在iOS中,你能看得见摸得着的东西基本上都是UIV ...

  10. Robot Framework-DatabaseLibrary数据库(MySql)

    Robot Framework-Mac版本安装 Robot Framework-Windows版本安装 Robot Framework-工具简介及入门使用 Robot Framework-Databa ...