技术标签: pyspider 爬虫 python Python
有2种实现方案:
1、使用pyspider开源框架,安装好pyspider并启动后,默认是本地的5001端口,新建一个爬虫项目,写下如下python代码实践爬去知乎的问题和评论数据,同时使用python-mysql,把爬到的数据存到自己建的一个数据库,把数据留给自己使用分析哈哈!
2、使用urllib,PyQuery,requests,BeautifulSoup等库自己实现一个简单的爬虫,可以爬取图片下载下来,存到数据库,或者爬取文本
本文共4部分:
import requests
import re
from bs4 import BeautifulSoup
def most_simple_crawl():
# 最简单的爬虫
content = requests.get('http://www.qiushibaike.com').content
soup = BeautifulSoup(content, 'html.parser')
for div in soup.find_all('div', {'class': 'content'}):
print div.text.strip()
if __name__ == '__main__':
most_simple_crawl()
# coding=utf-8
import re
import urllib2
import urllib
def crawl_taobao():
# 淘宝上搜索的关键词
key = "比基尼"
key = urllib2.quote(key)
headers = ("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0")
opener = urllib2.build_opener()
opener.addheaders = [headers]
urllib2.install_opener(opener)
# 分页爬取
for i in range(0, 4):
url = "https://s.taobao.com/search?q=" + key
data = urllib2.urlopen(url).read().decode("utf-8", "ignore")
pat = 'pic_url":"//(.*?)"'
imagelist = re.compile(pat).findall(data)
# 爬取每一页中所有的图片
for j in range(0, len(imagelist)):
thisimg = imagelist[j]
thisimgurl = "http://" + thisimg
# 保存到自己电脑的D盘
savefile = 'D:/pic/' + str(i) + str(j) + '.jpg'
urllib.urlretrieve(thisimgurl, filename=savefile)
if __name__ == '__main__':
crawl_taobao()
from pyspider.libs.base_handler import *
import MySQLdb
import random
class Handler(BaseHandler):
crawl_config = {
'headers':{
'User-Agent':'GoogleBot',
'Host':'www.zhihu.com',
}
}
def __init__(self):
self.db = MySQLdb.connect('localhost', 'root', '123456', 'onlineq', charset='utf8')
# 把爬到的知乎问题存到自己建的数据库中
def add_question(self,title,content,comment_count):
try:
cursor=self.db.cursor()
sql = 'insert into question(title, content, user_id, created_date,comment_count)values ("%s","%s", %d,now(),%d)'%(title,content,random.randint(20,26),comment_count)
print sql
cursor.execute(sql)
qid= cursor.lastrowid
print qid
self.db.commit()
return qid
except Exception, e:
self.db.rollback()
return 0
# 把爬到的问题评论存到自己建的数据库中
def add_comment(self,qid, comment):
try:
cursor=self.db.cursor()
sql='insert into comment (content, entity_type, entity_id, user_id, created_date) values("%s",100,%d,%d ,now())' % (comment, qid,random.randint(20,26))
print sql
cursor.execute(sql)
self.db.commit()
except Exception, e:
print e
self.db.rollback()
@every(minutes=24 * 60)
def on_start(self):
self.crawl('https://www.zhihu.com/topic/19552330/top-answers', callback=self.index_page,validate_cert=False)
@config(age=10 * 24 * 60 * 60)
def index_page(self, response):
for each in response.doc('a[data-za-detail-view-element_name="Title"]').items():
self.crawl(each.attr.href, callback=self.detail_page,validate_cert=False)
@config(priority=2)
def detail_page(self, response):
title = response.doc('h1.QuestionHeader-title').text()
content = response.doc('span.RichText.ztext').html()
items = response.doc('span.RichText.ztext.CopyrightRichText-richText').items()
if content==None:
content = ''
content = content.replace('"','\\"')
qid=self.add_question(title,content,sum(1 for x in items))
for each in response.doc('span.RichText.ztext.CopyrightRichText-richText').items():
self.add_comment(qid,each.html().replace('"','\\"'))
return {
"url": response.url,
"title": response.doc('title').text(),
}
from pyspider.libs.base_handler import *
import random
import MySQLdb
class Handler(BaseHandler):
crawl_config = {
}
def __init__(self):
self.db = MySQLdb.connect('localhost', 'root', '123456', 'onlineq', charset='utf8')
def add_question(self,title,content):
try:
cursor=self.db.cursor()
sql = 'insert into question(title, content, user_id, created_date,comment_count)values ("%s","%s", %d,now(),0)'%(title,content,random.randint(20,22))
print sql
cursor.execute(sql)
print cursor.lastrowid
self.db.commit()
except Exception, e:
self.db.rollback()
@every(minutes=24 * 60)
def on_start(self):
self.crawl('https://www.v2ex.com/', callback=self.index_page,validate_cert=False)
@config(age=10 * 24 * 60 * 60)
def index_page(self, response):
for each in response.doc('a[href^="https://www.v2ex.com/?tab="]').items():
self.crawl(each.attr.href, callback=self.tab_page,validate_cert=False)
@config(priority=2)
def tab_page(self, response):
for each in response.doc('a[href^="https://www.v2ex.com/go/"]').items():
self.crawl(each.attr.href, callback=self.board_page,validate_cert=False)
@config(priority=2)
def board_page(self, response):
for each in response.doc('a[href^="https://www.v2ex.com/t/"]').items():
url=each.attr.href
if url.find('#reply')>0:
url=url[0:url.find('#')]
self.crawl(url, callback=self.detail_page,validate_cert=False)
for each in response.doc('a.page_normal').items():
self.crawl(each.attr.href, callback=self.board_page,validate_cert=False)
@config(priority=2)
def detail_page(self, response):
title = response.doc('h1').text()
content = response.doc('div.topic_content').html().replace('"','\\"')
self.add_question(title,content)
return {
"url": response.url,
"title": response.doc('title').text(),
}
文章浏览阅读122次。还是A+BTime Limit: 2000/1000 MS (Java/Others)Memory Limit: 65536/32768 K (Java/Others)Total Submission(s): 24568Accepted Submission(s): 11729Problem Description读入两个小于10000的正整数A和B,计算A+B。...
文章浏览阅读419次。HEADERS:在BASIC的基础上,额外记录了请求和响应的头信息。FULL:记录所有请求和响应的明细,包括头信息、请求体、元数据。BASIC:仅记录请求的方法,URL以及响应状态码和执行时间。NONE:不记录任何日志信息,这是默认值。配置Feign日志有两种方式;方式二:java代码实现。注解中声明则代表某服务。方式一:配置文件方式。_feign 日志设置
文章浏览阅读155次。将容器管理的持久性 Bean 用于面向服务的体系结构本文将介绍如何使用 IBM WebSphere Process Server 对容器管理的持久性 (CMP) Bean的连接和持久性逻辑加以控制,使其可以存储在非关系数据库..._javax.ejb.objectnotfoundexception: no such entity!
文章浏览阅读1.5k次。基础java练习题一、递归实现跳台阶从第一级跳到第n级,有多少种跳法一次可跳一级,也可跳两级。还能跳三级import java.math.BigDecimal;import java.util.Scanner;public class Main{ public static void main(String[]args){ Scanner reader=new Scanner(System.in); while(reader.hasNext()){ _java 递归例题
文章浏览阅读1.5k次,点赞6次,收藏6次。目录1.串应用- 计算一个串的最长的真前后缀题目描述输入输出样例输入样例输出题解2.字符串替换(string)题目描述输入输出样例输入样例输出题解3.可重叠子串 (Ver. I)题目描述输入输出样例输入样例输出题解4.字符串操作(string)题目描述输入输出样例输入样例输出题解1.串应用- 计算一个串的最长的真前后缀题目描述给定一个串,如ABCDAB,则ABCDAB的真前缀有:{ A, AB,ABC, ABCD, ABCDA }ABCDAB的真后缀有:{ B, AB,DAB, CDAB, BCDAB_对存储在string数组内的所有以字符‘a’开始并以字符‘e’结尾的单词做加密处理。
文章浏览阅读68次。西安交通大学/算法设计与问题求解/树与二叉树/MOOC_算法设计与问题求解西安交通大学
文章浏览阅读1.6k次。问题:在Vue项目中出现如下错误提示:[Vue warn]: Computed property "totalPrice" was assigned to but it has no setter. (found in <Anonymous>)代码:<input v-model="totalPrice"/>原因:v-model命令,因Vue 的双向数据绑定原理 , 会自动操作 totalPrice, 对其进行set 操作而 totalPrice 作为计..._computed property "totalprice" was assigned to but it has no setter.
文章浏览阅读60次。十分暴力而简洁的解决方式:读取P和T的位置并自动生成唯一正确答案,将题给测点与之对比,不一样就给我爬!_basic 1003 case 1
文章浏览阅读422次。原标题:详解将Web项目War包部署到Tomcat服务器基本步骤详解将Web项目War包部署到Tomcat服务器基本步骤1 War包War包一般是在进行Web开发时,通常是一个网站Project下的所有源码的集合,里面包含前台HTML/CSS/JS的代码,也包含Java的代码。当开发人员在自己的开发机器上调试所有代码并通过后,为了交给测试人员测试和未来进行产品发布,都需要将开发人员的源码打包成Wa..._/opt/bosssoft/war/medical-web.war/web-inf/web.xml of module medical-web.war.
文章浏览阅读3k次,点赞3次,收藏13次。# -*- coding: utf-8 -*-# 简述:这里有四个数字,分别是:1、2、3、4#提问:能组成多少个互不相同且无重复数字的三位数?各是多少?def f(n):list=[]count=0for i in range(1,n+1):for j in range(1, n+1):for k in range(1, n+1):if i!=j and j!=k and i!=k:list.a..._python求从0到9任意组合成三位数数字不能重复并输出
文章浏览阅读1k次,点赞3次,收藏2次。<el-table-column prop="studentSex" label="性别" :formatter="sex"></el-table-column>然后就在vue的methods中写方法就OK了methods: { sex(row,index){ if(row.studentSex == 1){ return '男'; }else{ return '女'; }..._elementui table 性别
文章浏览阅读1.1k次。java文件操作之移动文件到指定的目录_java中怎么将pro.txt移动到design_mode_code根目录下