原创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. hibernate进行多表联合查询

    hibernate是按照hql语句来进行查询的, 里面所使用的表名, 其实是实体类的名字, hql语句的写法并没有多大差别, 是在返回结果的时候要稍微做一些处理 //使用hibernate进行多表查询 ...

  2. PHP查看当前端口号

    <?php echo "当前页面服务器IP地址为:"; echo $_SERVER["SERVER_ADDR"]; echo "<br / ...

  3. [学习笔记] 七步从AngularJS菜鸟到专家(4和5):指令和表达式 [转]

    这一篇包含了"AngularJS - 七步从菜鸟到专家"系列的第四篇(指令)和第五篇(表达式). 之前的几篇展示了我们应用的核心组件,以及如何设置搭建一个Angular.js应用.在这一部分,我们会厘 ...

  4. perl 对源文件内容修改 方法整理

    1, 利用Tie::File模块来直接对文件内容进行修改. #!/usr/bin/perl -w my $std="F160"; my $fast="FAST" ...

  5. 下载android 源码

    http://source.android.com/source/downloading.html 1.下载repo 官网:curl http://commondatastorage.googleap ...

  6. LeetCode OJ-- Clone Graph **@

    https://oj.leetcode.com/problems/clone-graph/ 图的拷贝,就是给一个图,再弄出一个一模一样的来. /** * Definition for undirect ...

  7. .NET调用window串口读取电子秤的数据

    Private serialPort As SerialPort  '定义 Public Function CreateSerialPort() As String        Dim strWei ...

  8. wamp链接mysql数据库

    一:链接到自带的数据库 1.打开mysql命令行 密码为空即回车2.输入use mysql 3.执行 update user set password=PASSWORD('123456') where ...

  9. 采用动态代理方式调用WEB服务(转载+整理)

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

  10. 安装windows git客户端

    从git官网下载安装包,双击安装,一路默认配置,直到完成 打开git bash,运行 ssh-keygen -t rsa -C "573215750@qq.com" 回车,输入“y ...