python3与python2迭代器的写法的区别

李魔佛 发表了文章 • 0 个评论 • 2929 次浏览 • 2019-06-26 11:22 • 来自相关话题

大部分相同,只是python2里面需要实现在类中实现next()方法,而python3里面需要实现__next__()方法。
 
附一个例子:
def iter_demo():

class DefineIter(object):

def __init__(self,length):
self.length = length
self.data = range(self.length)
self.index=0

def __iter__(self):
return self


def __next__(self):

if self.index >=self.length:
# return None
raise StopIteration

d = self.data[self.index]*50
self.index =self.index + 1

return d

a = DefineIter(10)
print(type(a))
for i in a:
print(i) 查看全部
大部分相同,只是python2里面需要实现在类中实现next()方法,而python3里面需要实现__next__()方法。
 
附一个例子:
def iter_demo():

class DefineIter(object):

def __init__(self,length):
self.length = length
self.data = range(self.length)
self.index=0

def __iter__(self):
return self


def __next__(self):

if self.index >=self.length:
# return None
raise StopIteration

d = self.data[self.index]*50
self.index =self.index + 1

return d

a = DefineIter(10)
print(type(a))
for i in a:
print(i)

PyCharm 快捷键快速插入当前时间

李魔佛 发表了文章 • 0 个评论 • 3766 次浏览 • 2019-06-26 09:18 • 来自相关话题

个人觉得这是一个非常常用的功能,不过需要自定义实现。
 
方式
通过 Live Template 快速添加时间

步骤
1、添加一个 Template Group 命名为 Common
2、添加一个 Live Template 设置如下
Abbreviation: time
Description : current time
Template Text: $time$

Edit Variables -> Expresssion : date("yyyy-MM-dd HH:mm:ss")



3、让设置生效
Define->Everywhere

4、使用
输入 time 后 按下tab键 就能转换为当前时间了
  查看全部
个人觉得这是一个非常常用的功能,不过需要自定义实现。
 
方式
通过 Live Template 快速添加时间

步骤
1、添加一个 Template Group 命名为 Common
2、添加一个 Live Template 设置如下
Abbreviation: time
Description : current time
Template Text: $time$

Edit Variables -> Expresssion : date("yyyy-MM-dd HH:mm:ss")



3、让设置生效
Define->Everywhere

4、使用
输入 time 后 按下tab键 就能转换为当前时间了

 

conda无法在win10下用命令行切换虚拟环境

李魔佛 发表了文章 • 0 个评论 • 5117 次浏览 • 2019-06-11 10:04 • 来自相关话题

虚拟环境已经安装好了
然后在PowerShell下运行activate py2,没有任何反应。(powershell是win7后面系统的增强命令行)
后来使用系统原始的cmd命令行,在运行里面敲入cmd,然后重新执行activate py2,问题得到解决了。
原因是兼容问题。 查看全部
虚拟环境已经安装好了
然后在PowerShell下运行activate py2,没有任何反应。(powershell是win7后面系统的增强命令行)
后来使用系统原始的cmd命令行,在运行里面敲入cmd,然后重新执行activate py2,问题得到解决了。
原因是兼容问题。

jupyter notebook格式的文件损坏如何修复

李魔佛 发表了文章 • 0 个评论 • 4372 次浏览 • 2019-06-08 13:44 • 来自相关话题

有时候用git同步时,造成了冲突后合并,jupyter notebook的文件被插入了诸如>>>>>HEAD,ORIGIN等字符,这时候再打开jupyter notebook文件(.ipynb后缀),会无法打开。修复过程:
 
使用下面的代码:
# 拯救损坏的jupyter 文件
import re
import codecs

pattern = re.compile('"source": \[(.*?)\]\s+\},',re.S)
filename = 'tushare_usage.ipynb'
with codecs.open(filename,encoding='utf8') as f:
content = f.read()

source = pattern.findall(content)
for s in source:
t=s.replace('\\n','')
t=re.sub('"','',t)
t=re.sub('(,$)','',t)
print(t)只要把你要修复的文件替换一下就可以了。 查看全部
有时候用git同步时,造成了冲突后合并,jupyter notebook的文件被插入了诸如>>>>>HEAD,ORIGIN等字符,这时候再打开jupyter notebook文件(.ipynb后缀),会无法打开。修复过程:
 
使用下面的代码:
# 拯救损坏的jupyter 文件
import re
import codecs

pattern = re.compile('"source": \[(.*?)\]\s+\},',re.S)
filename = 'tushare_usage.ipynb'
with codecs.open(filename,encoding='utf8') as f:
content = f.read()

source = pattern.findall(content)
for s in source:
t=s.replace('\\n','')
t=re.sub('"','',t)
t=re.sub('(,$)','',t)
print(t)
只要把你要修复的文件替换一下就可以了。

关于懒人听书爬虫的请教

python爬虫b842619045 回复了问题 • 3 人关注 • 2 个回复 • 3912 次浏览 • 2019-05-22 23:04 • 来自相关话题

requests直接post图片文件

python爬虫李魔佛 发表了文章 • 0 个评论 • 3415 次浏览 • 2019-05-17 16:32 • 来自相关话题

代码如下:
file_path=r'9927_15562445086485238.png'
file=open(file_path, 'rb').read()
r=requests.post(url=code_url,data=file)
print(r.text) 查看全部
代码如下:
    file_path=r'9927_15562445086485238.png'
file=open(file_path, 'rb').read()
r=requests.post(url=code_url,data=file)
print(r.text)

python的mixin类

李魔佛 发表了文章 • 0 个评论 • 2753 次浏览 • 2019-05-16 16:30 • 来自相关话题

A mixin is a limited form of multiple inheritance.
 
maxin类似多重继承的一种限制形式:
 关于Python的Mixin模式

像C或C++这类语言都支持多重继承,一个子类可以有多个父类,这样的设计常被人诟病。因为继承应该是个”is-a”关系。比如轿车类继承交通工具类,因为轿车是一个(“is-a”)交通工具。一个物品不可能是多种不同的东西,因此就不应该存在多重继承。不过有没有这种情况,一个类的确是需要继承多个类呢?

答案是有,我们还是拿交通工具来举例子,民航飞机是一种交通工具,对于土豪们来说直升机也是一种交通工具。对于这两种交通工具,它们都有一个功能是飞行,但是轿车没有。所以,我们不可能将飞行功能写在交通工具这个父类中。但是如果民航飞机和直升机都各自写自己的飞行方法,又违背了代码尽可能重用的原则(如果以后飞行工具越来越多,那会出现许多重复代码)。怎么办,那就只好让这两种飞机同时继承交通工具以及飞行器两个父类,这样就出现了多重继承。这时又违背了继承必须是”is-a”关系。这个难题该怎么破?

不同的语言给出了不同的方法,让我们先来看下Java。Java提供了接口interface功能,来实现多重继承:public abstract class Vehicle {
}

public interface Flyable {
public void fly();
}

public class FlyableImpl implements Flyable {
public void fly() {
System.out.println("I am flying");
}
}

public class Airplane extends Vehicle implements Flyable {
private flyable;

public Airplane() {
flyable = new FlyableImpl();
}

public void fly() {
flyable.fly();
}
}

现在我们的飞机同时具有了交通工具及飞行器两种属性,而且我们不需要重写飞行器中的飞行方法,同时我们没有破坏单一继承的原则。飞机就是一种交通工具,可飞行的能力是是飞机的属性,通过继承接口来获取。

回到主题,Python语言可没有接口功能,但是它可以多重继承。那Python是不是就该用多重继承来实现呢?是,也不是。说是,因为从语法上看,的确是通过多重继承实现的。说不是,因为它的继承依然遵守”is-a”关系,从含义上看依然遵循单继承的原则。这个怎么理解呢?我们还是看例子吧。class Vehicle(object):
pass

class PlaneMixin(object):
def fly(self):
print 'I am flying'

class Airplane(Vehicle, PlaneMixin):
pass

可以看到,上面的Airplane类实现了多继承,不过它继承的第二个类我们起名为PlaneMixin,而不是Plane,这个并不影响功能,但是会告诉后来读代码的人,这个类是一个Mixin类。所以从含义上理解,Airplane只是一个Vehicle,不是一个Plane。这个Mixin,表示混入(mix-in),它告诉别人,这个类是作为功能添加到子类中,而不是作为父类,它的作用同Java中的接口。

使用Mixin类实现多重继承要非常小心
首先它必须表示某一种功能,而不是某个物品,如同Java中的Runnable,Callable等
 
其次它必须责任单一,如果有多个功能,那就写多个Mixin类然后,它不依赖于子类的实现最后,子类即便没有继承这个Mixin类,也照样可以工作,就是缺少了某个功能。(比如飞机照样可以载客,就是不能飞了^_^)
 
原创文章,转载请注明出处
http://30daydo.com/article/480
  查看全部
A mixin is a limited form of multiple inheritance.
 
maxin类似多重继承的一种限制形式:
 关于Python的Mixin模式

像C或C++这类语言都支持多重继承,一个子类可以有多个父类,这样的设计常被人诟病。因为继承应该是个”is-a”关系。比如轿车类继承交通工具类,因为轿车是一个(“is-a”)交通工具。一个物品不可能是多种不同的东西,因此就不应该存在多重继承。不过有没有这种情况,一个类的确是需要继承多个类呢?

答案是有,我们还是拿交通工具来举例子,民航飞机是一种交通工具,对于土豪们来说直升机也是一种交通工具。对于这两种交通工具,它们都有一个功能是飞行,但是轿车没有。所以,我们不可能将飞行功能写在交通工具这个父类中。但是如果民航飞机和直升机都各自写自己的飞行方法,又违背了代码尽可能重用的原则(如果以后飞行工具越来越多,那会出现许多重复代码)。怎么办,那就只好让这两种飞机同时继承交通工具以及飞行器两个父类,这样就出现了多重继承。这时又违背了继承必须是”is-a”关系。这个难题该怎么破?

不同的语言给出了不同的方法,让我们先来看下Java。Java提供了接口interface功能,来实现多重继承:
public abstract class Vehicle {
}

public interface Flyable {
public void fly();
}

public class FlyableImpl implements Flyable {
public void fly() {
System.out.println("I am flying");
}
}

public class Airplane extends Vehicle implements Flyable {
private flyable;

public Airplane() {
flyable = new FlyableImpl();
}

public void fly() {
flyable.fly();
}
}


现在我们的飞机同时具有了交通工具及飞行器两种属性,而且我们不需要重写飞行器中的飞行方法,同时我们没有破坏单一继承的原则。飞机就是一种交通工具,可飞行的能力是是飞机的属性,通过继承接口来获取。

回到主题,Python语言可没有接口功能,但是它可以多重继承。那Python是不是就该用多重继承来实现呢?是,也不是。说是,因为从语法上看,的确是通过多重继承实现的。说不是,因为它的继承依然遵守”is-a”关系,从含义上看依然遵循单继承的原则。这个怎么理解呢?我们还是看例子吧。
class Vehicle(object):
pass

class PlaneMixin(object):
def fly(self):
print 'I am flying'

class Airplane(Vehicle, PlaneMixin):
pass


可以看到,上面的Airplane类实现了多继承,不过它继承的第二个类我们起名为PlaneMixin,而不是Plane,这个并不影响功能,但是会告诉后来读代码的人,这个类是一个Mixin类。所以从含义上理解,Airplane只是一个Vehicle,不是一个Plane。这个Mixin,表示混入(mix-in),它告诉别人,这个类是作为功能添加到子类中,而不是作为父类,它的作用同Java中的接口。

使用Mixin类实现多重继承要非常小心
  • 首先它必须表示某一种功能,而不是某个物品,如同Java中的Runnable,Callable等

 
  • 其次它必须责任单一,如果有多个功能,那就写多个Mixin类
  • 然后,它不依赖于子类的实现
  • 最后,子类即便没有继承这个Mixin类,也照样可以工作,就是缺少了某个功能。(比如飞机照样可以载客,就是不能飞了^_^)

 
原创文章,转载请注明出处
http://30daydo.com/article/480
 

正则表达式替换中文换行符【python】

python爬虫李魔佛 发表了文章 • 0 个评论 • 2857 次浏览 • 2019-05-13 11:02 • 来自相关话题

js里面的内容有中文的换行符。
使用正则表达式替换换行符。(也可以替换为任意字符)js=re.sub('\r\n','',js)
完毕。
js里面的内容有中文的换行符。
使用正则表达式替换换行符。(也可以替换为任意字符)
js=re.sub('\r\n','',js)

完毕。

request header显示Provisional headers are shown

python爬虫李魔佛 发表了文章 • 0 个评论 • 4847 次浏览 • 2019-05-13 10:07 • 来自相关话题

出现这个情况,一般是因为装了一些插件,比如屏蔽广告的插件 ad block导致的。
把插件卸载了问题就解决了。
出现这个情况,一般是因为装了一些插件,比如屏蔽广告的插件 ad block导致的。
把插件卸载了问题就解决了。

异步爬虫aiohttp post提交数据

python爬虫李魔佛 发表了文章 • 0 个评论 • 7722 次浏览 • 2019-05-08 16:40 • 来自相关话题

基本的用法:async def fetch(session,url, data):
async with session.post(url=url, data=data, headers=headers) as response:
return await response.json()
 完整的例子:import aiohttp
import asyncio

page = 30

post_data = {
'page': 1,
'pageSize': 10,
'keyWord': '',
'dpIds': '',
}

headers = {

"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.9",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
}

result=


async def fetch(session,url, data):
async with session.post(url=url, data=data, headers=headers) as response:
return await response.json()

async def parse(html):
xzcf_list = html.get('newtxzcfList')
if xzcf_list is None:
return
for i in xzcf_list:
result.append(i)

async def downlod(page):
data=post_data.copy()
data['page']=page
url = 'http://credit.chaozhou.gov.cn/tfieldTypeActionJson!initXzcfListnew.do'
async with aiohttp.ClientSession() as session:
html=await fetch(session,url,data)
await parse(html)

loop = asyncio.get_event_loop()
tasks=[asyncio.ensure_future(downlod(i)) for i in range(1,page)]
tasks=asyncio.gather(*tasks)
# print(tasks)
loop.run_until_complete(tasks)
# loop.close()
# print(result)
count=0
for i in result:
print(i.get('cfXdrMc'))
count+=1
print(f'total {count}') 查看全部
基本的用法:
async def fetch(session,url, data):
async with session.post(url=url, data=data, headers=headers) as response:
return await response.json()

 完整的例子:
import aiohttp
import asyncio

page = 30

post_data = {
'page': 1,
'pageSize': 10,
'keyWord': '',
'dpIds': '',
}

headers = {

"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.9",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.108 Safari/537.36",
"X-Requested-With": "XMLHttpRequest",
}

result=


async def fetch(session,url, data):
async with session.post(url=url, data=data, headers=headers) as response:
return await response.json()

async def parse(html):
xzcf_list = html.get('newtxzcfList')
if xzcf_list is None:
return
for i in xzcf_list:
result.append(i)

async def downlod(page):
data=post_data.copy()
data['page']=page
url = 'http://credit.chaozhou.gov.cn/tfieldTypeActionJson!initXzcfListnew.do'
async with aiohttp.ClientSession() as session:
html=await fetch(session,url,data)
await parse(html)

loop = asyncio.get_event_loop()
tasks=[asyncio.ensure_future(downlod(i)) for i in range(1,page)]
tasks=asyncio.gather(*tasks)
# print(tasks)
loop.run_until_complete(tasks)
# loop.close()
# print(result)
count=0
for i in result:
print(i.get('cfXdrMc'))
count+=1
print(f'total {count}')

python异步aiohttp爬虫 - 异步爬取链家数据

python爬虫李魔佛 发表了文章 • 0 个评论 • 2723 次浏览 • 2019-05-08 15:52 • 来自相关话题

import requests
from lxml import etree
import asyncio
import aiohttp
import pandas
import re
import math
import time

loction_info = ''' 1→杭州
2→武汉
3→北京
按ENTER确认:'''
loction_select = input(loction_info)
loction_dic = {'1': 'hz',
'2': 'wh',
'3': 'bj'}
city_url = 'https://{}.lianjia.com/ershoufang/'.format(loction_dic[loction_select])
down = input('请输入价格下限(万):')
up = input('请输入价格上限(万):')

inter_list = [(int(down), int(up))]


def half_inter(inter):
lower = inter[0]
upper = inter[1]
delta = int((upper - lower) / 2)
inter_list.remove(inter)
print('已经缩小价格区间', inter)
inter_list.append((lower, lower + delta))
inter_list.append((lower + delta, upper))


pagenum = {}


def get_num(inter):
url = city_url + 'bp{}ep{}/'.format(inter[0], inter[1])
r = requests.get(url).text
print(r)
num = int(etree.HTML(r).xpath("//h2[@class='total fl']/span/text()")[0].strip())
pagenum[(inter[0], inter[1])] = num
return num


totalnum = get_num(inter_list[0])

judge = True
while judge:
a = [get_num(x) > 3000 for x in inter_list]
if True in a:
judge = True
else:
judge = False
for i in inter_list:
if get_num(i) > 3000:
half_inter(i)
print('价格区间缩小完毕!')

url_lst = []
url_lst_failed = []
url_lst_successed = []
url_lst_duplicated = []

for i in inter_list:
totalpage = math.ceil(pagenum[i] / 30)
for j in range(1, totalpage + 1):
url = city_url + 'pg{}bp{}ep{}/'.format(j, i[0], i[1])
url_lst.append(url)
print('url列表获取完毕!')

info_lst = []


async def get_info(url):
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=5) as resp:
if resp.status != 200:
url_lst_failed.append(url)
else:
url_lst_successed.append(url)
r = await resp.text()
nodelist = etree.HTML(r).xpath("//ul[@class='sellListContent']/li")
# print('-------------------------------------------------------------')
# print('开始抓取第{}个页面的数据,共计{}个页面'.format(url_lst.index(url),len(url_lst)))
# print('开始抓取第{}个页面的数据,共计{}个页面'.format(url_lst.index(url), len(url_lst)))
# print('开始抓取第{}个页面的数据,共计{}个页面'.format(url_lst.index(url), len(url_lst)))
# print('-------------------------------------------------------------')
info_dic = {}
index = 1
print('开始抓取{}'.format(resp.url))
print('开始抓取{}'.format(resp.url))
print('开始抓取{}'.format(resp.url))
for node in nodelist:
try:
info_dic['title'] = node.xpath(".//div[@class='title']/a/text()")[0]
except:
info_dic['title'] = '/'
try:
info_dic['href'] = node.xpath(".//div[@class='title']/a/@href")[0]
except:
info_dic['href'] = '/'
try:
info_dic['xiaoqu'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[0]
except:
info_dic['xiaoqu'] = '/'
try:
info_dic['huxing'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[1]
except:
info_dic['huxing'] = '/'
try:
info_dic['area'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[2]
except:
info_dic['area'] = '/'
try:
info_dic['chaoxiang'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[3]
except:
info_dic['chaoxiang'] = '/'
try:
info_dic['zhuangxiu'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[4]
except:
info_dic['zhuangxiu'] = '/'
try:
info_dic['dianti'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[5]
except:
info_dic['dianti'] = '/'
try:
info_dic['louceng'] = re.findall('\((.*)\)', node.xpath(".//div[@class='positionInfo']/text()")[0])
except:
info_dic['louceng'] = '/'
try:
info_dic['nianxian'] = re.findall('\)(.*?)年', node.xpath(".//div[@class='positionInfo']/text()")[0])
except:
info_dic['nianxian'] = '/'
try:
info_dic['guanzhu'] = ''.join(re.findall('[0-9]', node.xpath(".//div[@class='followInfo']/text()")[
0].replace(' ', '').split('/')[0]))
except:
info_dic['guanzhu'] = '/'
try:
info_dic['daikan'] = ''.join(re.findall('[0-9]',
node.xpath(".//div[@class='followInfo']/text()")[0].replace(
' ', '').split('/')[1]))
except:
info_dic['daikan'] = '/'
try:
info_dic['fabu'] = node.xpath(".//div[@class='followInfo']/text()")[0].replace(' ', '').split('/')[
2]
except:
info_dic['fabu'] = '/'
try:
info_dic['totalprice'] = node.xpath(".//div[@class='totalPrice']/span/text()")[0]
except:
info_dic['totalprice'] = '/'
try:
info_dic['unitprice'] = node.xpath(".//div[@class='unitPrice']/span/text()")[0].replace('单价', '')
except:
info_dic['unitprice'] = '/'
if True in [info_dic['href'] in dic.values() for dic in info_lst]:
url_lst_duplicated.append(info_dic)
else:
info_lst.append(info_dic)
print('第{}条: {}→房屋信息抓取完毕!'.format(index, info_dic['title']))
index += 1
info_dic = {}


start = time.time()

# 首次抓取url_lst中的信息,部分url没有对其发起请求,不知道为什么
tasks = [asyncio.ensure_future(get_info(url)) for url in url_lst]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

# 将没有发起请求的url放入一个列表,对其进行循环抓取,直到所有url都被发起请求
url_lst_unrequested = []
for url in url_lst:
if url not in url_lst_successed or url_lst_failed:
url_lst_unrequested.append(url)
while len(url_lst_unrequested) > 0:
tasks_unrequested = [asyncio.ensure_future(get_info(url)) for url in url_lst_unrequested]
loop.run_until_complete(asyncio.wait(tasks_unrequested))
url_lst_unrequested = []
for url in url_lst:
if url not in url_lst_successed:
url_lst_unrequested.append(url)
end = time.time()
print('当前价格区间段内共有{}套二手房源\(包含{}条重复房源\),实际获得{}条房源信息。'.format(totalnum, len(url_lst_duplicated), len(info_lst)))
print('总共耗时{}秒'.format(end - start))

df = pandas.DataFrame(info_lst)
df.to_csv("ljwh.csv", encoding='gbk') 查看全部
import requests
from lxml import etree
import asyncio
import aiohttp
import pandas
import re
import math
import time

loction_info = ''' 1→杭州
2→武汉
3→北京
按ENTER确认:'''
loction_select = input(loction_info)
loction_dic = {'1': 'hz',
'2': 'wh',
'3': 'bj'}
city_url = 'https://{}.lianjia.com/ershoufang/'.format(loction_dic[loction_select])
down = input('请输入价格下限(万):')
up = input('请输入价格上限(万):')

inter_list = [(int(down), int(up))]


def half_inter(inter):
lower = inter[0]
upper = inter[1]
delta = int((upper - lower) / 2)
inter_list.remove(inter)
print('已经缩小价格区间', inter)
inter_list.append((lower, lower + delta))
inter_list.append((lower + delta, upper))


pagenum = {}


def get_num(inter):
url = city_url + 'bp{}ep{}/'.format(inter[0], inter[1])
r = requests.get(url).text
print(r)
num = int(etree.HTML(r).xpath("//h2[@class='total fl']/span/text()")[0].strip())
pagenum[(inter[0], inter[1])] = num
return num


totalnum = get_num(inter_list[0])

judge = True
while judge:
a = [get_num(x) > 3000 for x in inter_list]
if True in a:
judge = True
else:
judge = False
for i in inter_list:
if get_num(i) > 3000:
half_inter(i)
print('价格区间缩小完毕!')

url_lst = []
url_lst_failed = []
url_lst_successed = []
url_lst_duplicated = []

for i in inter_list:
totalpage = math.ceil(pagenum[i] / 30)
for j in range(1, totalpage + 1):
url = city_url + 'pg{}bp{}ep{}/'.format(j, i[0], i[1])
url_lst.append(url)
print('url列表获取完毕!')

info_lst = []


async def get_info(url):
async with aiohttp.ClientSession() as session:
async with session.get(url, timeout=5) as resp:
if resp.status != 200:
url_lst_failed.append(url)
else:
url_lst_successed.append(url)
r = await resp.text()
nodelist = etree.HTML(r).xpath("//ul[@class='sellListContent']/li")
# print('-------------------------------------------------------------')
# print('开始抓取第{}个页面的数据,共计{}个页面'.format(url_lst.index(url),len(url_lst)))
# print('开始抓取第{}个页面的数据,共计{}个页面'.format(url_lst.index(url), len(url_lst)))
# print('开始抓取第{}个页面的数据,共计{}个页面'.format(url_lst.index(url), len(url_lst)))
# print('-------------------------------------------------------------')
info_dic = {}
index = 1
print('开始抓取{}'.format(resp.url))
print('开始抓取{}'.format(resp.url))
print('开始抓取{}'.format(resp.url))
for node in nodelist:
try:
info_dic['title'] = node.xpath(".//div[@class='title']/a/text()")[0]
except:
info_dic['title'] = '/'
try:
info_dic['href'] = node.xpath(".//div[@class='title']/a/@href")[0]
except:
info_dic['href'] = '/'
try:
info_dic['xiaoqu'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[0]
except:
info_dic['xiaoqu'] = '/'
try:
info_dic['huxing'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[1]
except:
info_dic['huxing'] = '/'
try:
info_dic['area'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[2]
except:
info_dic['area'] = '/'
try:
info_dic['chaoxiang'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[3]
except:
info_dic['chaoxiang'] = '/'
try:
info_dic['zhuangxiu'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[4]
except:
info_dic['zhuangxiu'] = '/'
try:
info_dic['dianti'] = \
node.xpath(".//div[@class='houseInfo']")[0].xpath('string(.)').replace(' ', '').split('|')[5]
except:
info_dic['dianti'] = '/'
try:
info_dic['louceng'] = re.findall('\((.*)\)', node.xpath(".//div[@class='positionInfo']/text()")[0])
except:
info_dic['louceng'] = '/'
try:
info_dic['nianxian'] = re.findall('\)(.*?)年', node.xpath(".//div[@class='positionInfo']/text()")[0])
except:
info_dic['nianxian'] = '/'
try:
info_dic['guanzhu'] = ''.join(re.findall('[0-9]', node.xpath(".//div[@class='followInfo']/text()")[
0].replace(' ', '').split('/')[0]))
except:
info_dic['guanzhu'] = '/'
try:
info_dic['daikan'] = ''.join(re.findall('[0-9]',
node.xpath(".//div[@class='followInfo']/text()")[0].replace(
' ', '').split('/')[1]))
except:
info_dic['daikan'] = '/'
try:
info_dic['fabu'] = node.xpath(".//div[@class='followInfo']/text()")[0].replace(' ', '').split('/')[
2]
except:
info_dic['fabu'] = '/'
try:
info_dic['totalprice'] = node.xpath(".//div[@class='totalPrice']/span/text()")[0]
except:
info_dic['totalprice'] = '/'
try:
info_dic['unitprice'] = node.xpath(".//div[@class='unitPrice']/span/text()")[0].replace('单价', '')
except:
info_dic['unitprice'] = '/'
if True in [info_dic['href'] in dic.values() for dic in info_lst]:
url_lst_duplicated.append(info_dic)
else:
info_lst.append(info_dic)
print('第{}条: {}→房屋信息抓取完毕!'.format(index, info_dic['title']))
index += 1
info_dic = {}


start = time.time()

# 首次抓取url_lst中的信息,部分url没有对其发起请求,不知道为什么
tasks = [asyncio.ensure_future(get_info(url)) for url in url_lst]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))

# 将没有发起请求的url放入一个列表,对其进行循环抓取,直到所有url都被发起请求
url_lst_unrequested = []
for url in url_lst:
if url not in url_lst_successed or url_lst_failed:
url_lst_unrequested.append(url)
while len(url_lst_unrequested) > 0:
tasks_unrequested = [asyncio.ensure_future(get_info(url)) for url in url_lst_unrequested]
loop.run_until_complete(asyncio.wait(tasks_unrequested))
url_lst_unrequested = []
for url in url_lst:
if url not in url_lst_successed:
url_lst_unrequested.append(url)
end = time.time()
print('当前价格区间段内共有{}套二手房源\(包含{}条重复房源\),实际获得{}条房源信息。'.format(totalnum, len(url_lst_duplicated), len(info_lst)))
print('总共耗时{}秒'.format(end - start))

df = pandas.DataFrame(info_lst)
df.to_csv("ljwh.csv", encoding='gbk')

pycharm debug scrapy 报错 twisted.internet.error.ReactorNotRestartable

python爬虫李魔佛 发表了文章 • 0 个评论 • 6008 次浏览 • 2019-04-23 11:35 • 来自相关话题

没发现哪里不妥,以前debug调试scrapy一直没问题。 
后来才发现,
scrapy run的启动文件名不能命令为cmd.py !!!!!
我把scrapy的启动写到cmd.py里面
from scrapy import cmdline cmdline.execute('scrapy crawl xxxx'.split())
 
然后cmd.py和系统某个调试功能的库重名了。 查看全部
没发现哪里不妥,以前debug调试scrapy一直没问题。 
后来才发现,
scrapy run的启动文件名不能命令为cmd.py !!!!!
我把scrapy的启动写到cmd.py里面
from scrapy import cmdline cmdline.execute('scrapy crawl xxxx'.split())
 
然后cmd.py和系统某个调试功能的库重名了。

python不支持多重继承中的重复继承

李魔佛 发表了文章 • 0 个评论 • 2328 次浏览 • 2019-04-18 16:36 • 来自相关话题

代码如下:
class First(object):
def __init__(self):
print("first")

class Second(First):
def __init__(self):
print("second")

class Third(First,Second):
def __init__(self):
print("third")
运行代码会直接报错:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-c90f7b77d3e0> in <module>()
7 print("second")
8
----> 9 class Third(First,Second):
10 def __init__(self):
11 print("third")

TypeError: Cannot create a consistent method resolution order (MRO) for bases First, Second
  查看全部
代码如下:
class First(object):
def __init__(self):
print("first")

class Second(First):
def __init__(self):
print("second")

class Third(First,Second):
def __init__(self):
print("third")

运行代码会直接报错:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-6-c90f7b77d3e0> in <module>()
7 print("second")
8
----> 9 class Third(First,Second):
10 def __init__(self):
11 print("third")

TypeError: Cannot create a consistent method resolution order (MRO) for bases First, Second

 

gevent异步 入门教程(入坑)

李魔佛 发表了文章 • 0 个评论 • 2979 次浏览 • 2019-04-18 11:37 • 来自相关话题

code1
import time
import gevent
import requests
def foo():
print('Running in foo')

r=requests.get('http://30daydo.com')
print(r.status_code)
print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')

r=requests.get('http://www.qq.com') #
print(r.status_code)
print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))
上面的异步代码不起作用,因为requests阻塞了,所以用的时间和顺序执行的时间一样.
 
或者用以下代码替代:
import time
import gevent
import requests
def foo():
print('Running in foo')
time.sleep(2) # 这样子不起作用
print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')
time.sleep(2)
print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))
把访问网络部分使用sleep替代,那么最后的运行时间是2+2 =4秒,并不是2秒,那么要怎样才是2秒呢,需要改成以下的代码:
 
import time
import gevent
import requests
def foo():
print('Running in foo')

gevent.sleep(2) # 通过它各自yield向对方

print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')

gevent.sleep(2)

print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))
使用gevent.sleep()
这个函数才可以达到目的. 查看全部
code1
import time
import gevent
import requests
def foo():
print('Running in foo')

r=requests.get('http://30daydo.com')
print(r.status_code)
print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')

r=requests.get('http://www.qq.com') #
print(r.status_code)
print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))

上面的异步代码不起作用,因为requests阻塞了,所以用的时间和顺序执行的时间一样.
 
或者用以下代码替代:
import time
import gevent
import requests
def foo():
print('Running in foo')
time.sleep(2) # 这样子不起作用
print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')
time.sleep(2)
print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))

把访问网络部分使用sleep替代,那么最后的运行时间是2+2 =4秒,并不是2秒,那么要怎样才是2秒呢,需要改成以下的代码:
 
import time
import gevent
import requests
def foo():
print('Running in foo')

gevent.sleep(2) # 通过它各自yield向对方

print('Explicit context switch to foo again')

def bar():
print('Explicit context to bar')

gevent.sleep(2)

print('Implicit context switch back to bar')

start=time.time()
gevent.joinall([
gevent.spawn(foo),
gevent.spawn(bar),
])
print('time used {}'.format(time.time()-start))

使用gevent.sleep()
这个函数才可以达到目的.

python的pip安装mysqldb

李魔佛 发表了文章 • 0 个评论 • 2627 次浏览 • 2019-04-16 23:51 • 来自相关话题

换一个新环境,或者在另一台服务器上运行自己的程序,最烦就是pip安装各种依赖,尤其其他机器上的python不一致(你用的是python3,服务器用的是python2),或者两个系统都不一致。 这个时候pip安装第三方库就很折腾。
 
比如mysqldb这个库,windows用python2不知道怎样才能装上。 反正这个我几年装过,现在已经忘记怎么安装了。
今天又要装一遍,为了减轻痛苦,安装anaconda,然后使用conda install mysqldb,conda会帮你把依赖都解决掉。 不然你要装一堆的VC8,VC14, 等等。
 
然后等待一下,就安装好了。 查看全部
换一个新环境,或者在另一台服务器上运行自己的程序,最烦就是pip安装各种依赖,尤其其他机器上的python不一致(你用的是python3,服务器用的是python2),或者两个系统都不一致。 这个时候pip安装第三方库就很折腾。
 
比如mysqldb这个库,windows用python2不知道怎样才能装上。 反正这个我几年装过,现在已经忘记怎么安装了。
今天又要装一遍,为了减轻痛苦,安装anaconda,然后使用conda install mysqldb,conda会帮你把依赖都解决掉。 不然你要装一堆的VC8,VC14, 等等。
 
然后等待一下,就安装好了。

最流行的版本控制软件:git 个人笔记

李魔佛 发表了文章 • 0 个评论 • 2964 次浏览 • 2019-04-16 23:37 • 来自相关话题

最流行的版本控制软件:git
========================

git已经是当前最流行的版本控制软件之一了。全世界的程序员都在使用它。它出自linus大神之手,现在被用于内
核的版本控制。在最流行的代码托管软件github,你几乎可以找到所有开源项目的代码。

版块控制软件:我需要吗?
-----------------------

的确对于许多人——尤其是非程序员,他们可能不会想到已经出现了专门的版本控制的软件。但其实多人对版本控
制其实都有类似的需求,举个例子,Tom是社团的秘书处成员,他们经常需要做的事情就是写活动文档,然后不停地
改改到大家都觉得可以了。

不幸运的话,Tom可能有个文件夹叫“openSUSE活动策划",里面有这样的一堆文件”openSUSE活动策划", "活动策
划1", "活动策划2", "活动策划3", "活动策划4" ... "活动策划20" (可怜的Tom,一份文档改了不少于20次)

这种作法很有效,因为我们可能发现第5个版本的策划有问题,我们准备在第3个版本上面重新来过。但是也看到,
这个作法有些很丑陋的地方:一份文件,我们留了20个备份,而且还要注意文件名。

如果可以这样就好了:文件夹上只有一个“openSUSE活动策划",但当我需要第5个版本的时候,我来一个”给我还
原到第5个版本吧!“,然后这时候我们打开这个文件,它就是第5个版本的了。类似的,我们可以取出任意的版本


这就是版本控制。这种事情在程序里面发生的太多了,于是出现了各种版本控制软件。事实上,有些项目已经发展
到第1000+甚至更高的版本数了……

单线的工作流
------------

我们可以把我们的一个项目想象为一个仓库,然后我们可以把我们的东西塞进仓库里面,也可以把想要的东西拿出
来。而git则是仓库的管理员。下面是一个例子,希望有一个直观的印象,不求完全的理解和掌握。

```bash
mkdir myproject // 假设myproject是工作目录
cd myproject
git init // git <- (init) ,告诉仓库管理员,在当前目录初始化
echo 'Eat the banana' > file // 编辑了一个文件
git add file // 加入仓库
git commit -m 'add first file' // 提交更改
echo 'Eat the apply' > file // 修改了这个文件
git add file // 加入仓库
git commit -m 'update first file' // 再提交更改
```

这时候我们就有两个commit了,我们来看看工作日志:

```bash
git log

# 以下是输出
# commit ac1371173b4e630ddaebda3f9f5d948b36146c07
# Author: Norman Mo <LTaoist@@@>
# Date: Thu Jun 27 21:59:10 2013 +0800
#
# update first file
#
# commit 3c43cc913454f92bb4b80c56ba45e4ffaf556fc0
# Author: Norman Mo <LTaoist6@@@@>
# Date: Thu Jun 27 21:58:48 2013 +0800
#
# add first file
```

看到了,我们提交了两次。我们来看看现在file里面是什么:

```bash
cat file # 显然输出是 'Eat the apply'
# 现在,我们来拿回第一个版本的file文件
git checkout 3c43cc913454f92bb4b80c56ba45e4ffaf556fc0 -- file
cat file # 这时候就是eat banana了
```

这种工作的方式是单人使用最常见的方式,写一点代码,提交一下到仓库里面。写一点,提交到仓库里面。然后出
问题的时候就回退过去。git非常强大,基本上你想到的他都可以做到,提交到仓库的数据基本不会丢失,像时间机
器一样控制着代码。

多人协作
--------

git非常强大,上面只是一个功能。考虑Tom的秘书处有两个人,他们在同时写。其中Tom写前6章,他的同伴写第7~
12章。

这时候可以考虑用这种工作的方式:设立一个公共的仓库。Tom维护自己的版本,他的同伴维护自己的版本。然后大
家定期把代码合并到公共仓库上面,然后定期把新的版本取回来合并再提交到公共仓库。

如果他们用纯文本,得益于一些文本分析的方法,几乎不需要校对就可以做到。

```
git commit -m 'finish ch5' // 假设此时Tom写完了第5章
git push // Tom将代码推送到远程仓库
```

```
git commit -m 'finish ch11' // 假设此时Tom的同伴完成了第11章
git pull // pull会将最新版本拉下来,合并,然后推送到远程仓库
```

实际上工作中,为了不混淆,会新开一个分支来开发新的特性,然后对分支进行合并。

代码自动发布
-----------

另一个很强大的功能是可以实现代码的自动发布。事实上,很多云就有使用这个。具体来说,利用git的hooks,当
服务器收到一个push,服务器可以自动运行一些脚本。也可以在客户端使用hooks,当客户端准备push的时候,客户
端先运行一些脚本。

例如,我们希望在每次服务器收到push以后,杀死全部的 `p` 进程,然后重开 `p` 进程。我们可以修改 `hooks/
post-receive` :

```
echo "Killing all p process..."
killall -9 p
echo "Restart p process..."
p
```

更多更多更多……
---------------

这份教程就到这里了,更多的自己马上动手去试试吧!

在openSUSE的安装方法:

```
sudo zypper in git
```

默认应该就装了。

一般linux命令查看帮助都是 `--help` 选项:

```
git --help
```

此外,对一个子命令也是有help看的:

```
git init --help
```

这里有一个交互教程,在浏览器上面跑的模拟git的运行的,有兴趣的试试:

<http://try.github.io/>

github的help文档写得很不错,推荐一下:

<https://help.github.com/>

书籍有个远近闻名的《Pro Git》,而且有中文版的,虽然我认为这本书太厚了。。。但似乎就这么一本书……

<http://git-scm.com/book/zh>

国内有个gitcafe,也是做git托管的,他们也有整理一份help:

<https://gitcafe.com/GitCafe/Help>

记得,上面只是一个演示,多试试push,多尝试。有一天你会喜欢用这个有效的工具的。

很有用!!! 查看全部

最流行的版本控制软件:git
========================

git已经是当前最流行的版本控制软件之一了。全世界的程序员都在使用它。它出自linus大神之手,现在被用于内
核的版本控制。在最流行的代码托管软件github,你几乎可以找到所有开源项目的代码。

版块控制软件:我需要吗?
-----------------------

的确对于许多人——尤其是非程序员,他们可能不会想到已经出现了专门的版本控制的软件。但其实多人对版本控
制其实都有类似的需求,举个例子,Tom是社团的秘书处成员,他们经常需要做的事情就是写活动文档,然后不停地
改改到大家都觉得可以了。

不幸运的话,Tom可能有个文件夹叫“openSUSE活动策划",里面有这样的一堆文件”openSUSE活动策划", "活动策
划1", "活动策划2", "活动策划3", "活动策划4" ... "活动策划20" (可怜的Tom,一份文档改了不少于20次)

这种作法很有效,因为我们可能发现第5个版本的策划有问题,我们准备在第3个版本上面重新来过。但是也看到,
这个作法有些很丑陋的地方:一份文件,我们留了20个备份,而且还要注意文件名。

如果可以这样就好了:文件夹上只有一个“openSUSE活动策划",但当我需要第5个版本的时候,我来一个”给我还
原到第5个版本吧!“,然后这时候我们打开这个文件,它就是第5个版本的了。类似的,我们可以取出任意的版本


这就是版本控制。这种事情在程序里面发生的太多了,于是出现了各种版本控制软件。事实上,有些项目已经发展
到第1000+甚至更高的版本数了……

单线的工作流
------------

我们可以把我们的一个项目想象为一个仓库,然后我们可以把我们的东西塞进仓库里面,也可以把想要的东西拿出
来。而git则是仓库的管理员。下面是一个例子,希望有一个直观的印象,不求完全的理解和掌握。

```bash
mkdir myproject // 假设myproject是工作目录
cd myproject
git init // git <- (init) ,告诉仓库管理员,在当前目录初始化
echo 'Eat the banana' > file // 编辑了一个文件
git add file // 加入仓库
git commit -m 'add first file' // 提交更改
echo 'Eat the apply' > file // 修改了这个文件
git add file // 加入仓库
git commit -m 'update first file' // 再提交更改
```

这时候我们就有两个commit了,我们来看看工作日志:

```bash
git log

# 以下是输出
# commit ac1371173b4e630ddaebda3f9f5d948b36146c07
# Author: Norman Mo <LTaoist@@@>
# Date: Thu Jun 27 21:59:10 2013 +0800
#
# update first file
#
# commit 3c43cc913454f92bb4b80c56ba45e4ffaf556fc0
# Author: Norman Mo <LTaoist6@@@@>
# Date: Thu Jun 27 21:58:48 2013 +0800
#
# add first file
```

看到了,我们提交了两次。我们来看看现在file里面是什么:

```bash
cat file # 显然输出是 'Eat the apply'
# 现在,我们来拿回第一个版本的file文件
git checkout 3c43cc913454f92bb4b80c56ba45e4ffaf556fc0 -- file
cat file # 这时候就是eat banana了
```

这种工作的方式是单人使用最常见的方式,写一点代码,提交一下到仓库里面。写一点,提交到仓库里面。然后出
问题的时候就回退过去。git非常强大,基本上你想到的他都可以做到,提交到仓库的数据基本不会丢失,像时间机
器一样控制着代码。

多人协作
--------

git非常强大,上面只是一个功能。考虑Tom的秘书处有两个人,他们在同时写。其中Tom写前6章,他的同伴写第7~
12章。

这时候可以考虑用这种工作的方式:设立一个公共的仓库。Tom维护自己的版本,他的同伴维护自己的版本。然后大
家定期把代码合并到公共仓库上面,然后定期把新的版本取回来合并再提交到公共仓库。

如果他们用纯文本,得益于一些文本分析的方法,几乎不需要校对就可以做到。

```
git commit -m 'finish ch5' // 假设此时Tom写完了第5章
git push // Tom将代码推送到远程仓库
```

```
git commit -m 'finish ch11' // 假设此时Tom的同伴完成了第11章
git pull // pull会将最新版本拉下来,合并,然后推送到远程仓库
```

实际上工作中,为了不混淆,会新开一个分支来开发新的特性,然后对分支进行合并。

代码自动发布
-----------

另一个很强大的功能是可以实现代码的自动发布。事实上,很多云就有使用这个。具体来说,利用git的hooks,当
服务器收到一个push,服务器可以自动运行一些脚本。也可以在客户端使用hooks,当客户端准备push的时候,客户
端先运行一些脚本。

例如,我们希望在每次服务器收到push以后,杀死全部的 `p` 进程,然后重开 `p` 进程。我们可以修改 `hooks/
post-receive` :

```
echo "Killing all p process..."
killall -9 p
echo "Restart p process..."
p
```

更多更多更多……
---------------

这份教程就到这里了,更多的自己马上动手去试试吧!

在openSUSE的安装方法:

```
sudo zypper in git
```

默认应该就装了。

一般linux命令查看帮助都是 `--help` 选项:

```
git --help
```

此外,对一个子命令也是有help看的:

```
git init --help
```

这里有一个交互教程,在浏览器上面跑的模拟git的运行的,有兴趣的试试:

<http://try.github.io/>

github的help文档写得很不错,推荐一下:

<https://help.github.com/>

书籍有个远近闻名的《Pro Git》,而且有中文版的,虽然我认为这本书太厚了。。。但似乎就这么一本书……

<http://git-scm.com/book/zh>

国内有个gitcafe,也是做git托管的,他们也有整理一份help:

<https://gitcafe.com/GitCafe/Help>

记得,上面只是一个演示,多试试push,多尝试。有一天你会喜欢用这个有效的工具的。

很有用!!!

python 爬虫使用urlretrieve下载时一直报错

李魔佛 回复了问题 • 2 人关注 • 1 个回复 • 5894 次浏览 • 2019-04-11 09:53 • 来自相关话题

CentOS Zookeeper无法启动:Error contacting service,It is probably not running

python爬虫李魔佛 发表了文章 • 0 个评论 • 4438 次浏览 • 2019-04-09 19:20 • 来自相关话题

启动:
./kafka-server-start.sh -daemon ../config/server.properties
报错:
Error contacting service,It is probably not running
 
关闭重启,杀进程,看端口是否被占用。无果。
后来看了下防火墙,OMG,有一台机子的防火墙没有关闭。
 
手工关闭后问题就解决了。
 
关闭防火墙命令:
systemctl stop firewalld.service #关闭防火墙
systemctl disable firewalld.service #禁止启动防火墙 查看全部
启动:
./kafka-server-start.sh -daemon ../config/server.properties
报错:
Error contacting service,It is probably not running
 
关闭重启,杀进程,看端口是否被占用。无果。
后来看了下防火墙,OMG,有一台机子的防火墙没有关闭。
 
手工关闭后问题就解决了。
 
关闭防火墙命令:
systemctl stop firewalld.service #关闭防火墙
systemctl disable firewalld.service #禁止启动防火墙

numpy datetime转为date,pandas的日期类型转为python的daetime

李魔佛 发表了文章 • 0 个评论 • 7648 次浏览 • 2019-04-08 15:40 • 来自相关话题

dataframe的数据格式是这样子的:





 
info看一下里面的数据类型:<class 'pandas.core.frame.DataFrame'>
RangeIndex: 307 entries, 0 to 306
Data columns (total 7 columns):
日期 307 non-null datetime64[ns]
指数 307 non-null float64
成交额(亿元) 307 non-null float64
涨跌 307 non-null float64
涨跌额 307 non-null float64
转债数目 307 non-null float64
剩余规模 307 non-null float64
dtypes: datetime64[ns](1), float64(6)
memory usage: 16.9 KB
日期 307 non-null datetime64[ns]
 
然后转为list看看:
a=list(df['日期'].values)
如果使用上面的方法,返回的是这样的数据:[numpy.datetime64('2017-12-29T00:00:00.000000000'),
numpy.datetime64('2018-01-02T00:00:00.000000000'),
numpy.datetime64('2018-01-03T00:00:00.000000000'),
numpy.datetime64('2018-01-04T00:00:00.000000000'),
numpy.datetime64('2018-01-05T00:00:00.000000000'),
numpy.datetime64('2018-01-08T00:00:00.000000000'),
numpy.datetime64('2018-01-09T00:00:00.000000000'),
numpy.datetime64('2018-01-10T00:00:00.000000000'),
numpy.datetime64('2018-01-11T00:00:00.000000000'),
numpy.datetime64('2018-01-12T00:00:00.000000000'),
numpy.datetime64('2018-01-15T00:00:00.000000000'),
numpy.datetime64('2018-01-16T00:00:00.000000000'),
numpy.datetime64('2018-01-17T00:00:00.000000000'),
 
如何转化为python的daetime格式呢?
 
可以使用内置的:s.dt.to_pydatetime()
s为df的一列,也就是series数据格式b=list(df['日期'].dt.to_pydatetime())得到的是[datetime.datetime(2017, 12, 29, 0, 0),
datetime.datetime(2018, 1, 2, 0, 0),
datetime.datetime(2018, 1, 3, 0, 0),
datetime.datetime(2018, 1, 4, 0, 0),
datetime.datetime(2018, 1, 5, 0, 0),
datetime.datetime(2018, 1, 8, 0, 0),
datetime.datetime(2018, 1, 9, 0, 0),
datetime.datetime(2018, 1, 10, 0, 0),
datetime.datetime(2018, 1, 11, 0, 0),
datetime.datetime(2018, 1, 12, 0, 0),
datetime.datetime(2018, 1, 15, 0, 0)
为了不想要小时,分钟,秒的数据,可以清洗一下:
b=[i.strftime('%Y-%m-%d') for i in b]
 
得到:['2017-12-29',
'2018-01-02',
'2018-01-03',
'2018-01-04',
'2018-01-05',
'2018-01-08',
'2018-01-09',
'2018-01-10',
'2018-01-11',
'2018-01-12',
'2018-01-15',
'2018-01-16',
'2018-01-17',] 
  查看全部
dataframe的数据格式是这样子的:

d1.PNG

 
info看一下里面的数据类型:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 307 entries, 0 to 306
Data columns (total 7 columns):
日期 307 non-null datetime64[ns]
指数 307 non-null float64
成交额(亿元) 307 non-null float64
涨跌 307 non-null float64
涨跌额 307 non-null float64
转债数目 307 non-null float64
剩余规模 307 non-null float64
dtypes: datetime64[ns](1), float64(6)
memory usage: 16.9 KB

日期 307 non-null datetime64[ns]
 
然后转为list看看:
a=list(df['日期'].values)
如果使用上面的方法,返回的是这样的数据:
[numpy.datetime64('2017-12-29T00:00:00.000000000'),
numpy.datetime64('2018-01-02T00:00:00.000000000'),
numpy.datetime64('2018-01-03T00:00:00.000000000'),
numpy.datetime64('2018-01-04T00:00:00.000000000'),
numpy.datetime64('2018-01-05T00:00:00.000000000'),
numpy.datetime64('2018-01-08T00:00:00.000000000'),
numpy.datetime64('2018-01-09T00:00:00.000000000'),
numpy.datetime64('2018-01-10T00:00:00.000000000'),
numpy.datetime64('2018-01-11T00:00:00.000000000'),
numpy.datetime64('2018-01-12T00:00:00.000000000'),
numpy.datetime64('2018-01-15T00:00:00.000000000'),
numpy.datetime64('2018-01-16T00:00:00.000000000'),
numpy.datetime64('2018-01-17T00:00:00.000000000'),

 
如何转化为python的daetime格式呢?
 
可以使用内置的:s.dt.to_pydatetime()
s为df的一列,也就是series数据格式
b=list(df['日期'].dt.to_pydatetime())
得到的是
[datetime.datetime(2017, 12, 29, 0, 0),
datetime.datetime(2018, 1, 2, 0, 0),
datetime.datetime(2018, 1, 3, 0, 0),
datetime.datetime(2018, 1, 4, 0, 0),
datetime.datetime(2018, 1, 5, 0, 0),
datetime.datetime(2018, 1, 8, 0, 0),
datetime.datetime(2018, 1, 9, 0, 0),
datetime.datetime(2018, 1, 10, 0, 0),
datetime.datetime(2018, 1, 11, 0, 0),
datetime.datetime(2018, 1, 12, 0, 0),
datetime.datetime(2018, 1, 15, 0, 0)

为了不想要小时,分钟,秒的数据,可以清洗一下:
b=[i.strftime('%Y-%m-%d') for i in b]
 
得到:
['2017-12-29',
'2018-01-02',
'2018-01-03',
'2018-01-04',
'2018-01-05',
'2018-01-08',
'2018-01-09',
'2018-01-10',
'2018-01-11',
'2018-01-12',
'2018-01-15',
'2018-01-16',
'2018-01-17',]
 
 

kindle收不到python推送的附件,但是同邮件的客户端可以。求助。

李魔佛 回复了问题 • 2 人关注 • 1 个回复 • 4052 次浏览 • 2019-04-08 10:03 • 来自相关话题

python datetime模块:timestamp转为本地时间(东八区)

李魔佛 发表了文章 • 0 个评论 • 7615 次浏览 • 2019-04-04 15:15 • 来自相关话题

一般timestamp时间戳格式为10位,如果是13位,则需要除以1000,

1554369904000
为例,计算这个数字的本地时间。
 
如果使用
t=1554369904000
datetime.datetime.fromtimestamp(t/1000)
 
得到的是:
(2019, 4, 4, 17, 25, 4)
 
然而这个时间并不是我想要的,和我想要的时间差了8个时区。
 
那么可以使用
datetime.datetime.utcfromtimestamp(t/1000)
这个返回的就是我想要的时间了
(2019, 4, 4, 9, 25, 4)
 
 
引用:
timestamp转换为datetime
要把timestamp转换为datetime,使用datetime提供的fromtimestamp()方法:

>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t))
2015-04-19 12:20:00
注意到timestamp是一个浮点数,它没有时区的概念,而datetime是有时区的。上述转换是在timestamp和本地时间做转换。

本地时间是指当前操作系统设定的时区。例如北京时区是东8区,则本地时间:

2015-04-19 12:20:00
实际上就是UTC+8:00时区的时间:

2015-04-19 12:20:00 UTC+8:00
而此刻的格林威治标准时间与北京时间差了8小时,也就是UTC+0:00时区的时间应该是:

2015-04-19 04:20:00 UTC+0:00
timestamp也可以直接被转换到UTC标准时区的时间:

>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t)) # 本地时间
2015-04-19 12:20:00
>>> print(datetime.utcfromtimestamp(t)) # UTC时间
2015-04-19 04:20:00
 
  查看全部
一般timestamp时间戳格式为10位,如果是13位,则需要除以1000,

1554369904000
为例,计算这个数字的本地时间。
 
如果使用
t=1554369904000
datetime.datetime.fromtimestamp(t/1000)
 
得到的是:
(2019, 4, 4, 17, 25, 4)
 
然而这个时间并不是我想要的,和我想要的时间差了8个时区。
 
那么可以使用
datetime.datetime.utcfromtimestamp(t/1000)
这个返回的就是我想要的时间了
(2019, 4, 4, 9, 25, 4)
 
 
引用:
timestamp转换为datetime
要把timestamp转换为datetime,使用datetime提供的fromtimestamp()方法:

>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t))
2015-04-19 12:20:00
注意到timestamp是一个浮点数,它没有时区的概念,而datetime是有时区的。上述转换是在timestamp和本地时间做转换。

本地时间是指当前操作系统设定的时区。例如北京时区是东8区,则本地时间:

2015-04-19 12:20:00
实际上就是UTC+8:00时区的时间:

2015-04-19 12:20:00 UTC+8:00
而此刻的格林威治标准时间与北京时间差了8小时,也就是UTC+0:00时区的时间应该是:

2015-04-19 04:20:00 UTC+0:00
timestamp也可以直接被转换到UTC标准时区的时间:

>>> from datetime import datetime
>>> t = 1429417200.0
>>> print(datetime.fromtimestamp(t)) # 本地时间
2015-04-19 12:20:00
>>> print(datetime.utcfromtimestamp(t)) # UTC时间
2015-04-19 04:20:00

 
 

【python】pymongo find_one_and_update的用法

python爬虫李魔佛 发表了文章 • 0 个评论 • 13742 次浏览 • 2019-04-04 11:31 • 来自相关话题

原生的mongo语句是这样的:db.collection.findOneAndUpdate(
<filter>,
<update>,
{
projection: <document>,
sort: <document>,
maxTimeMS: <number>,
upsert: <boolean>,
returnNewDocument: <boolean>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)
转换成python pymongo是这样的:>>> db.example.find_one_and_update(
... {'_id': 'userid'},
... {'$inc': {'seq': 1}},
... projection={'seq': True, '_id': False},
... return_document=ReturnDocument.AFTER)
上面的语句的意思是:
找到_id 为userid的值得文档,然后把该文档中的seq的值+1,然后返回seq的数据,不显示_id列
最后返回的数据是这样的:

{'seq': 2}
 
注意
findOneAndUpdate
是获取mongo文档中第一条满足条件的数据并做修改。该函数是线程安全的。意思就是在多个线程中操作,不会对同一条数据进行获取修改。
也就是该操作是原子操作。
 
ReturnDocument 引用的库
 
class pymongo.collection.ReturnDocument
 
在开头 from pymongo.collection import ReturnDocument
 
原创文章
转载请注明出处:
http://30daydo.com/article/445 查看全部
原生的mongo语句是这样的:
db.collection.findOneAndUpdate(
<filter>,
<update>,
{
projection: <document>,
sort: <document>,
maxTimeMS: <number>,
upsert: <boolean>,
returnNewDocument: <boolean>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ]
}
)

转换成python pymongo是这样的:
>>> db.example.find_one_and_update(
... {'_id': 'userid'},
... {'$inc': {'seq': 1}},
... projection={'seq': True, '_id': False},
... return_document=ReturnDocument.AFTER)

上面的语句的意思是:
找到_id 为userid的值得文档,然后把该文档中的seq的值+1,然后返回seq的数据,不显示_id列
最后返回的数据是这样的:

{'seq': 2}
 
注意
findOneAndUpdate
是获取mongo文档中第一条满足条件的数据并做修改。该函数是线程安全的。意思就是在多个线程中操作,不会对同一条数据进行获取修改。
也就是该操作是原子操作。
 
ReturnDocument 引用的库
 
class pymongo.collection.ReturnDocument
 
在开头 from pymongo.collection import ReturnDocument
 
原创文章
转载请注明出处:
http://30daydo.com/article/445

scrapy-redis使用redis集群进行分布式爬取

python爬虫李魔佛 发表了文章 • 2 个评论 • 7361 次浏览 • 2019-04-03 17:05 • 来自相关话题

正常情况单机的redis可以满足scrapy-redis进行分布式爬取,可是如果单机的redis的内存过小,很容易导致系统内存不够,读取数据缓慢,如果使用docker运行redis,更加可能导致redis的容器的进程被杀掉。(笔者就曾经经常遇到这种情况,机器内存才8GB,上面跑了N个docker容器,一旦内存吃紧,某个容器就被kill掉,导致爬虫经常出问题)。
 
使用redis集群可以增加redis集体内存,防止出现上面的情况。
 
scrapy redis-cluster很简单,只需要按照以下步骤:
 
1. 按照库
pip install scrapy-redis-cluster
 
2. 修改settings文件
 
# Redis集群地址
REDIS_MASTER_NODES = [
{"host": "192.168.10.233", "port": "30001"},
{"host": "192.168.10.234", "port": "30002"},
{"host": "192.168.10.235", "port": "30003"},
]

# 使用的哈希函数数,默认为6
BLOOMFILTER_HASH_NUMBER = 6

# Bloomfilter使用的Redis内存位,30表示2 ^ 30 = 128MB,默认为22 (1MB 可去重130W URL)
BLOOMFILTER_BIT = 22

# 不清空redis队列
SCHEDULER_PERSIST = True
# 调度队列
SCHEDULER = "scrapy_redis_cluster.scheduler.Scheduler"
# 去重
DUPEFILTER_CLASS = "scrapy_redis_cluster.dupefilter.RFPDupeFilter"
# queue
SCHEDULER_QUEUE_CLASS = 'scrapy_redis_cluster.queue.PriorityQueue'
然后就可以运行啦。 查看全部
正常情况单机的redis可以满足scrapy-redis进行分布式爬取,可是如果单机的redis的内存过小,很容易导致系统内存不够,读取数据缓慢,如果使用docker运行redis,更加可能导致redis的容器的进程被杀掉。(笔者就曾经经常遇到这种情况,机器内存才8GB,上面跑了N个docker容器,一旦内存吃紧,某个容器就被kill掉,导致爬虫经常出问题)。
 
使用redis集群可以增加redis集体内存,防止出现上面的情况。
 
scrapy redis-cluster很简单,只需要按照以下步骤:
 
1. 按照库
pip install scrapy-redis-cluster
 
2. 修改settings文件
 
# Redis集群地址
REDIS_MASTER_NODES = [
{"host": "192.168.10.233", "port": "30001"},
{"host": "192.168.10.234", "port": "30002"},
{"host": "192.168.10.235", "port": "30003"},
]

# 使用的哈希函数数,默认为6
BLOOMFILTER_HASH_NUMBER = 6

# Bloomfilter使用的Redis内存位,30表示2 ^ 30 = 128MB,默认为22 (1MB 可去重130W URL)
BLOOMFILTER_BIT = 22

# 不清空redis队列
SCHEDULER_PERSIST = True
# 调度队列
SCHEDULER = "scrapy_redis_cluster.scheduler.Scheduler"
# 去重
DUPEFILTER_CLASS = "scrapy_redis_cluster.dupefilter.RFPDupeFilter"
# queue
SCHEDULER_QUEUE_CLASS = 'scrapy_redis_cluster.queue.PriorityQueue'

然后就可以运行啦。

【Dataframe warning】Try using .loc[row_indexer,col_indexer] = value instead

李魔佛 发表了文章 • 0 个评论 • 10862 次浏览 • 2019-04-02 22:48 • 来自相关话题

使用dataframe直接赋值操作时
 
df['当前日期'] = datetime.date.today()
 
会出现下面的警告信息
Try using .loc[row_indexer,col_indexer] = value instead 
 
虽然得到的最终结果是正常的,可是为什么会出现上面的警告呢?
 
因为上面的操作如果稍微复杂点,那么就可能导致赋值失败。 因为中间会产生一个切片的临时副本。
 
比如:
df
A B C D E
0 5 0 3 3 7
1 9 3 5 2 4
2 7 6 8 8 1
如果想把A列中大于5的数换成100,如何操作 ?
 
A B C D E
0 5 0 3 3 7
1 1000 3 5 2 4
2 1000 6 8 8 1

df[df.A > 5]['A'] = 1000
 
上面的这个表达式是不会生效的。
 
要生效,需要写成以下:
df.loc[df.A > 5, 'A'] = 1000
 
为什么呢?
因为df[df.A]得到是一个临时切片结果,等于一个中间变量,然后在这个中间变量上的A列上做赋值操作,但是最原始的df却没有被改变。
或者你可以这样写
df=df[df.A>5]
df.A=1000
 
 
  查看全部
使用dataframe直接赋值操作时
 
df['当前日期'] = datetime.date.today()
 
会出现下面的警告信息
Try using .loc[row_indexer,col_indexer] = value instead 
 
虽然得到的最终结果是正常的,可是为什么会出现上面的警告呢?
 
因为上面的操作如果稍微复杂点,那么就可能导致赋值失败。 因为中间会产生一个切片的临时副本。
 
比如:
df
A B C D E
0 5 0 3 3 7
1 9 3 5 2 4
2 7 6 8 8 1

如果想把A列中大于5的数换成100,如何操作 ?
 
      A  B  C  D  E
0 5 0 3 3 7
1 1000 3 5 2 4
2 1000 6 8 8 1


df[df.A > 5]['A'] = 1000
 
上面的这个表达式是不会生效的。
 
要生效,需要写成以下:
df.loc[df.A > 5, 'A'] = 1000
 
为什么呢?
因为df[df.A]得到是一个临时切片结果,等于一个中间变量,然后在这个中间变量上的A列上做赋值操作,但是最原始的df却没有被改变。
或者你可以这样写
df=df[df.A>5]
df.A=1000
 
 
 

python析构函数的执行顺序

李魔佛 发表了文章 • 0 个评论 • 3027 次浏览 • 2019-04-01 21:28 • 来自相关话题

在python里面,由于有自动回收内存的机制,所以析构函数的用处要比C++弱得多。 
 
下面看代码:
 
class Foobar(object):

def __init__(self):
print('class start')

def __del__(self):
print('class end')

def main()
obj = Foobar()
print('where is del?')
print('main end')

main()
上面的代码输出结果是什么呢? 卖个关子,自己执行看看吧。 查看全部
在python里面,由于有自动回收内存的机制,所以析构函数的用处要比C++弱得多。 
 
下面看代码:
 
class Foobar(object):

def __init__(self):
print('class start')

def __del__(self):
print('class end')

def main()
obj = Foobar()
print('where is del?')
print('main end')

main()

上面的代码输出结果是什么呢? 卖个关子,自己执行看看吧。

pycharm中格式化json字符

李魔佛 发表了文章 • 0 个评论 • 26937 次浏览 • 2019-03-29 09:25 • 来自相关话题

首先把json字符保存为json后缀,然后看看json字符串中是否用的双引号,注意,单引号不起作用,要把单引号替换成双引号,然后按快捷键ctrl+alt+L 就可以快速格式化json了。
 
效果如下
 





 
首先把json字符保存为json后缀,然后看看json字符串中是否用的双引号,注意,单引号不起作用,要把单引号替换成双引号,然后按快捷键ctrl+alt+L 就可以快速格式化json了。
 
效果如下
 

json.PNG

 

scrapy命令行执行传递多个参数给spider 动态传参

python爬虫李魔佛 发表了文章 • 0 个评论 • 6921 次浏览 • 2019-03-28 11:24 • 来自相关话题

有时候在命令行执行scrapy,比如scrapy crawl spiderXXXX,如果我想要传递一个自定义的参数进去给scrapy,比如我想传递一个爬取的页码数目,我要每次爬取10页。
 
那么需要在spider中定义一个构造函数
  def __init__(self,page=None,*args, **kwargs):
super(Gaode,self).__init__(*args, **kwargs)
self.page=page


def start_requests(self):
XXXXXX 调用self.page 即可
yield Request(XXXX)
 
然后在启动scrapy的时候赋予参数的值:
 
scrapy crawl spider -a page=10
 
就可以动态传入参数
 
原创文章
转载请注明出处:http://30daydo.com/article/436
  查看全部
有时候在命令行执行scrapy,比如scrapy crawl spiderXXXX,如果我想要传递一个自定义的参数进去给scrapy,比如我想传递一个爬取的页码数目,我要每次爬取10页。
 
那么需要在spider中定义一个构造函数
 
    def __init__(self,page=None,*args, **kwargs):
super(Gaode,self).__init__(*args, **kwargs)
self.page=page


def start_requests(self):
XXXXXX 调用self.page 即可
yield Request(XXXX)

 
然后在启动scrapy的时候赋予参数的值:
 
scrapy crawl spider -a page=10
 
就可以动态传入参数
 
原创文章
转载请注明出处:http://30daydo.com/article/436
 

学习强国Python自动化代码

python爬虫李魔佛 发表了文章 • 1 个评论 • 38638 次浏览 • 2019-03-27 17:45 • 来自相关话题

话不多说,爱国爱党爱人民!!! 本代码转载至github其他人,与本人无关。
 
# _*_ coding: utf-8 _*_

from selenium import webdriver
import time

__author__ = 'Silent_Coder'
__date__ = '2019/3/12 22:41'

HOME_PAGE = 'https://www.xuexi.cn/'
VIDEO_LINK = 'https://www.xuexi.cn/a191dbc3067d516c3e2e17e2e08953d6/b87d700beee2c44826a9202c75d18c85.html?pageNumber=39'
LONG_VIDEO_LINK = 'https://www.xuexi.cn/f65dae4a57fe21fcc36f3506d660891c/b2e5aa79be613aed1f01d261c4a2ae17.html'
LONG_VIDEO_LINK2 = 'https://www.xuexi.cn/0040db2a403b0b9303a68b9ae5a4cca0/b2e5aa79be613aed1f01d261c4a2ae17.html'
TEST_VIDEO_LINK = 'https://www.xuexi.cn/8e35a343fca20ee32c79d67e35dfca90/7f9f27c65e84e71e1b7189b7132b4710.html'
SCORES_LINK = 'https://pc.xuexi.cn/points/my-points.html'
LOGIN_LINK = 'https://pc.xuexi.cn/points/login.html'
ARTICLES_LINK = 'https://www.xuexi.cn/d05cad69216e688d304bb91ef3aac4c6/9a3668c13f6e303932b5e0e100fc248b.html'

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
browser = webdriver.Chrome(executable_path=r'D:\OneDrive\Python\selenium\chromedriver.exe',options=options)


def login_simulation():
"""模拟登录"""
# 方式一:使用cookies方式
# 先自己登录,然后复制token值覆盖
# cookies = {'name': 'token', 'value': ''}
# browser.add_cookie(cookies)

# 方式二:自己扫码登录
browser.get(LOGIN_LINK)
browser.maximize_window()
browser.execute_script("var q=document.documentElement.scrollTop=1000")
time.sleep(10)
browser.get(HOME_PAGE)
print("模拟登录完毕\n")


def watch_videos():
"""观看视频"""
browser.get(VIDEO_LINK)
videos = browser.find_elements_by_xpath("//div[@id='Ck3ln2wlyg3k00']")
spend_time = 0

for i, video in enumerate(videos):
if i > 6:
break
video.click()
all_handles = browser.window_handles
browser.switch_to_window(all_handles[-1])
browser.get(browser.current_url)

# 点击播放
browser.find_element_by_xpath("//div[@class='outter']").click()
# 获取视频时长
video_duration_str = browser.find_element_by_xpath("//span[@class='duration']").get_attribute('innerText')
video_duration = int(video_duration_str.split(':')[0]) * 60 + int(video_duration_str.split(':')[1])
# 保持学习,直到视频结束
time.sleep(video_duration + 3)
spend_time += video_duration + 3
browser.close()
browser.switch_to_window(all_handles[0])

# if spend_time < 3010:
# browser.get(LONG_VIDEO_LINK)
# browser.execute_script("var q=document.documentElement.scrollTop=850")
# try:
# browser.find_element_by_xpath("//div[@class='outter']").click()
# except:
# pass
#
# # 观看剩下的时间
# time.sleep(3010 - spend_time)
browser.get(TEST_VIDEO_LINK)
time.sleep(3010 - spend_time)
print("播放视频完毕\n")


def read_articles():
"""阅读文章"""
browser.get(ARTICLES_LINK)
articles = browser.find_elements_by_xpath("//div[@id='Ca4gvo4bwg7400']")
for index, article in enumerate(articles):
if index > 7:
break
article.click()
all_handles = browser.window_handles
browser.switch_to_window(all_handles[-1])
browser.get(browser.current_url)
for i in range(0, 2000, 100):

js_code = "var q=document.documentElement.scrollTop=" + str(i)
browser.execute_script(js_code)
time.sleep(5)
for i in range(2000, 0, -100):
js_code = "var q=document.documentElement.scrollTop=" + str(i)
browser.execute_script(js_code)
time.sleep(5)
time.sleep(80)
browser.close()
browser.switch_to_window(all_handles[0])
print("阅读文章完毕\n")


def get_scores():
"""获取当前积分"""
browser.get(SCORES_LINK)
time.sleep(2)
gross_score = browser.find_element_by_xpath("//*[@id='app']/div/div[2]/div/div[2]/div[2]/span[1]")\
.get_attribute('innerText')
today_score = browser.find_element_by_xpath("//span[@class='my-points-points']").get_attribute('innerText')
print("当前总积分:" + str(gross_score))
print("今日积分:" + str(today_score))
print("获取积分完毕,即将退出\n")


if __name__ == '__main__':
login_simulation() # 模拟登录
read_articles() # 阅读文章
watch_videos() # 观看视频
get_scores() # 获得今日积分
browser.quit() 查看全部
话不多说,爱国爱党爱人民!!! 本代码转载至github其他人,与本人无关。
 
# _*_ coding: utf-8 _*_

from selenium import webdriver
import time

__author__ = 'Silent_Coder'
__date__ = '2019/3/12 22:41'

HOME_PAGE = 'https://www.xuexi.cn/'
VIDEO_LINK = 'https://www.xuexi.cn/a191dbc3067d516c3e2e17e2e08953d6/b87d700beee2c44826a9202c75d18c85.html?pageNumber=39'
LONG_VIDEO_LINK = 'https://www.xuexi.cn/f65dae4a57fe21fcc36f3506d660891c/b2e5aa79be613aed1f01d261c4a2ae17.html'
LONG_VIDEO_LINK2 = 'https://www.xuexi.cn/0040db2a403b0b9303a68b9ae5a4cca0/b2e5aa79be613aed1f01d261c4a2ae17.html'
TEST_VIDEO_LINK = 'https://www.xuexi.cn/8e35a343fca20ee32c79d67e35dfca90/7f9f27c65e84e71e1b7189b7132b4710.html'
SCORES_LINK = 'https://pc.xuexi.cn/points/my-points.html'
LOGIN_LINK = 'https://pc.xuexi.cn/points/login.html'
ARTICLES_LINK = 'https://www.xuexi.cn/d05cad69216e688d304bb91ef3aac4c6/9a3668c13f6e303932b5e0e100fc248b.html'

options = webdriver.ChromeOptions()
options.add_experimental_option('excludeSwitches', ['enable-automation'])
browser = webdriver.Chrome(executable_path=r'D:\OneDrive\Python\selenium\chromedriver.exe',options=options)


def login_simulation():
"""模拟登录"""
# 方式一:使用cookies方式
# 先自己登录,然后复制token值覆盖
# cookies = {'name': 'token', 'value': ''}
# browser.add_cookie(cookies)

# 方式二:自己扫码登录
browser.get(LOGIN_LINK)
browser.maximize_window()
browser.execute_script("var q=document.documentElement.scrollTop=1000")
time.sleep(10)
browser.get(HOME_PAGE)
print("模拟登录完毕\n")


def watch_videos():
"""观看视频"""
browser.get(VIDEO_LINK)
videos = browser.find_elements_by_xpath("//div[@id='Ck3ln2wlyg3k00']")
spend_time = 0

for i, video in enumerate(videos):
if i > 6:
break
video.click()
all_handles = browser.window_handles
browser.switch_to_window(all_handles[-1])
browser.get(browser.current_url)

# 点击播放
browser.find_element_by_xpath("//div[@class='outter']").click()
# 获取视频时长
video_duration_str = browser.find_element_by_xpath("//span[@class='duration']").get_attribute('innerText')
video_duration = int(video_duration_str.split(':')[0]) * 60 + int(video_duration_str.split(':')[1])
# 保持学习,直到视频结束
time.sleep(video_duration + 3)
spend_time += video_duration + 3
browser.close()
browser.switch_to_window(all_handles[0])

# if spend_time < 3010:
# browser.get(LONG_VIDEO_LINK)
# browser.execute_script("var q=document.documentElement.scrollTop=850")
# try:
# browser.find_element_by_xpath("//div[@class='outter']").click()
# except:
# pass
#
# # 观看剩下的时间
# time.sleep(3010 - spend_time)
browser.get(TEST_VIDEO_LINK)
time.sleep(3010 - spend_time)
print("播放视频完毕\n")


def read_articles():
"""阅读文章"""
browser.get(ARTICLES_LINK)
articles = browser.find_elements_by_xpath("//div[@id='Ca4gvo4bwg7400']")
for index, article in enumerate(articles):
if index > 7:
break
article.click()
all_handles = browser.window_handles
browser.switch_to_window(all_handles[-1])
browser.get(browser.current_url)
for i in range(0, 2000, 100):

js_code = "var q=document.documentElement.scrollTop=" + str(i)
browser.execute_script(js_code)
time.sleep(5)
for i in range(2000, 0, -100):
js_code = "var q=document.documentElement.scrollTop=" + str(i)
browser.execute_script(js_code)
time.sleep(5)
time.sleep(80)
browser.close()
browser.switch_to_window(all_handles[0])
print("阅读文章完毕\n")


def get_scores():
"""获取当前积分"""
browser.get(SCORES_LINK)
time.sleep(2)
gross_score = browser.find_element_by_xpath("//*[@id='app']/div/div[2]/div/div[2]/div[2]/span[1]")\
.get_attribute('innerText')
today_score = browser.find_element_by_xpath("//span[@class='my-points-points']").get_attribute('innerText')
print("当前总积分:" + str(gross_score))
print("今日积分:" + str(today_score))
print("获取积分完毕,即将退出\n")


if __name__ == '__main__':
login_simulation() # 模拟登录
read_articles() # 阅读文章
watch_videos() # 观看视频
get_scores() # 获得今日积分
browser.quit()

scrapyd 日志文件中文乱码 解决方案

python爬虫李魔佛 发表了文章 • 0 个评论 • 4284 次浏览 • 2019-03-27 17:13 • 来自相关话题

用网页打开scrapyd的后台管理页面后,选择日志,会发现里面的中文是乱码。即使下载下来看也是乱码。
网上一般的解决方法是修改scrapyd的源码,增加一个utf8的编码页面,需要重新写一个html的页面框架,对于一般只是看看日志的朋友来说,没必要这么大刀阔斧的。
 
可以直接使用postman来打开日志文件,里面的中文是正常的。





  查看全部
用网页打开scrapyd的后台管理页面后,选择日志,会发现里面的中文是乱码。即使下载下来看也是乱码。
网上一般的解决方法是修改scrapyd的源码,增加一个utf8的编码页面,需要重新写一个html的页面框架,对于一般只是看看日志的朋友来说,没必要这么大刀阔斧的。
 
可以直接使用postman来打开日志文件,里面的中文是正常的。

scrapyd.PNG

 

最新版的anaconda无法使用pip安装软件:报错 SSL module is not available

李魔佛 发表了文章 • 0 个评论 • 6468 次浏览 • 2019-03-21 14:06 • 来自相关话题

错误信息:CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://mirrors.ustc.edu.cn/an ... gt%3B
Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
SSLError(MaxRetryError('HTTPSConnectionPool(host=\'mirrors.ustc.edu.cn\', port=443): Max retries exceeded with url: /anaconda/cloud/conda-forge/win-64/repodata.json (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available."))'))
折腾了很久,最新版的anaconda使用的是python3.7,也按照网上的方法,把openssl安装了,可是问题还是没有得到解决。
 
无奈下只能下载其他版本的anaconda。 可以到这里下载:
https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/ 
下载一个旧版本的anaconda,然后问题就得到解决了。
 
 
############ 更新 ############## 
 
新建一个 .condarc 文件,在 windows下的用户名目录下 ,  如 administrator下,
输入以下的内容:
 
channels:
- http://mirrors.tuna.tsinghua.e ... main/
- http://mirrors.tuna.tsinghua.e ... onda/
- http://mirrors.tuna.tsinghua.e ... free/
show_channel_urls: true
ssl_verify: true
重新下载即可。 查看全部
错误信息:
CondaHTTPError: HTTP 000 CONNECTION FAILED for url <https://mirrors.ustc.edu.cn/an ... gt%3B
Elapsed: -

An HTTP error occurred when trying to retrieve this URL.
HTTP errors are often intermittent, and a simple retry will get you on your way.
SSLError(MaxRetryError('HTTPSConnectionPool(host=\'mirrors.ustc.edu.cn\', port=443): Max retries exceeded with url: /anaconda/cloud/conda-forge/win-64/repodata.json (Caused by SSLError("Can\'t connect to HTTPS URL because the SSL module is not available."))'))

折腾了很久,最新版的anaconda使用的是python3.7,也按照网上的方法,把openssl安装了,可是问题还是没有得到解决。
 
无奈下只能下载其他版本的anaconda。 可以到这里下载:
https://mirrors.tuna.tsinghua.edu.cn/anaconda/archive/ 
下载一个旧版本的anaconda,然后问题就得到解决了。
 
 
############ 更新 ############## 
 
新建一个 .condarc 文件,在 windows下的用户名目录下 ,  如 administrator下,
输入以下的内容:
 
channels:
- http://mirrors.tuna.tsinghua.e ... main/
- http://mirrors.tuna.tsinghua.e ... onda/
- http://mirrors.tuna.tsinghua.e ... free/
show_channel_urls: true
ssl_verify: true

重新下载即可。