python--selenium简单模拟百度搜索点击器

python--selenium简单模拟百度搜索点击器
发布时间:2018-02-28 来源:网络 上传者:用户
关键字: selenium 模拟 简单 点击 搜索 百度
发表文章
摘要:用途:简单模拟用户点击百度搜索结果页,可延展为点击竞价,SEO作弊等多种功能所需module:selenium,time备注:因为是简单模拟,所以只是模拟器的雏形,并无防作弊机制。仅供参考。#coding=utf-8fromseleniumimportwebdriverimporttimebrowser=webdriver.Firefox()#启动Firefox浏览器url1='http://www.baidu.com/s?wd=马尔代夫'#马尔代夫的百度搜索页url2='h

用途:简单模拟用户点击百度搜索结果页,可延展为点击竞价,SEO作弊等多种功能所需module:selenium,time备注:因为是简单模拟,所以只是模拟器的雏形,并无防作弊机制。仅供参考。#coding=utf-8
from selenium import webdriver
import timebrowser = webdriver.Firefox() # 启动Firefox浏览器
url1 = 'http://www.baidu.com/s?wd=马尔代夫' # 马尔代夫的百度搜索页
url2 = 'http://scrapy.org/' # 测试页面1
url3 = 'http://news.yahoo.com/air-strike-libyan-city-misrata-clashes-near-oil-135039996.html' # 测试页面2
browser.get(url1) # 打开页面
browser.maximize_window() # 浏览器窗口最大化
res = browser.find_elements_by_xpath("//h3[@class='t c-gap-bottom-small']") # 使用xpath查找页面中的h3元素
for r in res: # 页面中h3元素有多个,所以需要遍历
t = r.find_element_by_xpath("a") # h3元素下的a标签
print '%s - %s' % (t.text, type(t.text)) # 打印a标签的标题以及文本格式
if u'途牛' in t.text: # 判断标题中是否有途牛,如果有则点击
print 'yes' # 判断结果
t.click() # 点击这个a链接print len(res) # 打印h3标签的总量
=============================================================================

 


快速激活码生成V2
发布时间:2018-02-28 来源:网络 上传者:用户
关键字: 激活 生成 快速
发表文章
摘要:不久之前我发布了一个激活码生成的Python代码 比较简陋.也有不少朋友给予了回复和支持 也有朋友提出了意见.今天呢,我把热心朋友提出的意见整合到了代码里.也添加了新功能Title 使激活码前面几个字符串保持一致( 便于一些有意思的事情发生 )另外 如果觉得会重复我觉得问题不大.如果是正式部署需要用到我的代码 你可以在mysql里增加一个字段 领取id也好 领取Mail也好.匹配验证码的

不久之前我发布了一个激活码生成的Python代码 比较简陋.也有不少朋友给予了回复和支持 也有朋友提出了意见.今天呢,我把热心朋友提出的意见整合到了代码里.也添加了新功能Title 使激活码前面几个字符串保持一致( 便于一些有意思的事情发生 )另外 如果觉得会重复我觉得问题不大.如果是正式部署需要用到我的代码 你可以在mysql里增加一个字段 领取id也好 领取Mail也好.匹配验证码的时候多增加一个字段的验证即可. 就算有重复 第二验证字段不通过 也是不影响的.再想想 一共由48个字母+10个数字 组成的无序字符串 得多少才会遇到一个重复的啊? 激活码长度过小几率会更大.不过激活码这个东西 14~16位我觉得很好了.
# coding=utf-8
# config 为配置词典
# y 是长度 最终生产出来的验证码是 长度 = Y - title的长度
# x 是循环次数 生成数量
# title 是激活码最前固定字符串 留空代表不使用
import string
import random
import MySQLdb
db = MySQLdb.connect("localhost","root","123456","Python")
cursor = db.cursor()
cursor.execute("DROP TABLE IF EXISTS JHM") # 如果有JHM这个数据库就删除
cursor.execute(
"""CREATE TABLE JHM(id int(11) primary key AUTO_INCREMENT, jhm CHAR(20) NOT NULL , status CHAR(1) NOT NULL)""")
config = {'y': 10, 'x': 20, 'title':"Dota"}def jhm(num):
b = ''.join(random.sample(string.ascii_letters + string.digits, num))
return bdef sql(w):
try:
cursor.execute(w)
except:
db.rollback()for z in range(config['x']):
w ="INSERT INTO JHM(jhm,status)VALUES ('%s','%s')"% (
config['title'] + jhm(config['y'] - len(config['title'])), '0')
sql(w)
db.commit()
db.close()
==============================================================


文件结构扁平化
发布时间:2018-02-28 来源:网络 上传者:用户
关键字: 扁平化 结构 文件
发表文章
摘要:azure的存储是一种扁平化结构也就是说,在容器中没有路径,所有的全部为文件,那么对于系统中嵌套的文件夹要保持原结构,应该怎么办呢?例如:尼古拉喜欢对一切看到的东西进行分类。 有一次,斯蒂芬送了他一个标签机作为他的生日礼物, 机器人把在船上的每个面的标签撕了几个星期。 从那时起,他归类在他的实验室的所有试剂, 图书馆的书和在桌子上笔记。 但后来他得知 python 字典,并分类所有索菲亚的机器人的可能的配置

azure的存储是一种扁平化结构也就是说,在容器中没有路径,所有的全部为文件,那么对于系统中嵌套的文件夹要保持原结构,应该怎么办呢?例如:尼古拉喜欢对一切看到的东西进行分类。 有一次,斯蒂芬送了他一个标签机作为他的生日礼物, 机器人把在船上的每个面的标签撕了几个星期。 从那时起,他归类在他的实验室的所有试剂, 图书馆的书和在桌子上笔记。 但后来他得知 python 字典,并分类所有索菲亚的机器人的可能的配置。 现在,这些文件被组织在一个很深的嵌套结构, 但索菲亚并不喜欢这样。让我们帮助索菲亚扁平化这些字典。Python字典是一种可以用来方便地存储和处理配置的数据类型。它允许你通过键来创建嵌套结构来存储数据。您将得到一个字典,其中的键是字符串,值是字符串或字典。我们的目标是使字典扁平化,但保存的结构中的键。其结果应该是一个字典没有嵌套的字典。键应包含原来的字典中的父键的路径。在路径中的键是由以“/”分开。如果值是一个空的字典,那么它应该由一个空字符串("")所取代。让我们来看一个例子:{ "name": { "first": "One", "last": "Drone" }, "job": "scout", "recent": {}, "additional": { "place": { "zone": "1", "cell": "2"} }}其结果将是:{"name/first": "One", #one parent "name/last": "Drone", "job": "scout", #root key "recent": "", #empty dict "additional/place/zone": "1", #third level "additional/place/cell": "2"}
def flatten(dictionary):
stack = [((), dictionary)]
result = {}
while stack:
path, current = stack.pop()
if not current:
result["/".join((path ))] =""
for k, v in current.items():
if isinstance(v, dict):
stack.append((path + (k,), v))
else:
result["/".join((path + (k,)))] = v
return result
=========================================================


风行网vip电影播放地址解析
发布时间:2018-02-28 来源:网络 上传者:用户
关键字: 风行 解析 地址 播放 电影 VIP
发表文章
摘要:通过http请求分析,获取视频最终的cdn播放地址,也就是一个mp4视频。vip电影想看就看,你懂的。仅用于学习交流目的,最长24小时后请删除^_^#!/usr/bin/evnpython#coding=utf8#author:aliyunzixun@xxx.com#date:2014-12-26importsysimportosimporttimeimporturllib2importcStringIO,gzipimportlxml.htmlimportreimportjs

通过http请求分析,获取视频最终的cdn播放地址,也就是一个mp4视频。vip电影想看就看,你懂的。仅用于学习交流目的,最长24小时后请删除^_^
#!/usr/bin/evn python
#coding=utf8
#author:aliyunzixun@xxx.com
#date:2014-12-26
import sys
import os
import time
import urllib2
import cStringIO, gzip
import lxml.html
import re
import json
import random
def createRequest(url, referer = None):
req = urllib2.Request(
urllib2.quote(url.split('#')[0].encode('utf8'), safe ="%/:=&;?~#+!$,;'@()*[]"),
headers = {"Accept":"application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5",
"Accept-Charset":"GBK,utf-8;q=0.7,*;q=0.3",
"Accept-Encoding":"gzip",
"Accept-Language":"zh-CN,zh;q=0.8",
"Cache-Control":"max-age=0",
"Connection":"keep-alive",
"User-Agent":"Mozilla/5.0 (Windows NT 5.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2",
})
if referer is not None:
req.add_header('Referer', referer)
return req
def getContent(url, referer = None):
f = urllib2.urlopen(createRequest(url, referer), timeout = 15)
data = f.read()
if data[:6] == 'x1fx8bx08x00x00x00':
data = gzip.GzipFile(fileobj = cStringIO.StringIO(data)).read()
f.close()
return data
def getCdnUrl(apiUrl, referer = None):
content = getContent(apiUrl, referer)
data = json.loads(content)
token = data['token']
for resource in data['fsps']:
fspUrl = resource['url']
if resource['clarity'] == 'super-dvd':
fspUrl = resource['url']
fsp = re.findall("fsp://(w+)", fspUrl)[0]
if fsp == '':
return None
else:
timestamp = int(time.time())
cdnUrl = 'http://jobsfe.funshion.com/query/v1/mp4/{0}.json?clifz=fun&;mac=&;tm={1}&;token={2}'.format(fsp, timestamp, token)
return cdnUrl
def getPlayUrl(cdnUrl, referer = None):
content = getContent(cdnUrl, referer)
data = json.loads(content)
if data['return'] == 'succ':
playUrls = data['playlist'][0]['urls']
return playUrls[random.randint(0, len(playUrls)-1)]
return None
if __name__ == '__main__':
if len(sys.argv) < 2 or sys.argv[1].startswith('http') is None:
print 'Usage: python fun.py http://www.fun.tv/vplay/m-115946/'
print 'Please input the url to be parse'
sys.exit()
videoUrl = sys.argv[1]
vid = int(re.findall("vplay/m-(d+)", videoUrl)[0])
apiUrl = 'http://api.fun.tv/ajax/get_webplayinfo/{0}/1/mp4?user=funshion'.format(vid)
cdnUrl = getCdnUrl(apiUrl, videoUrl)
playUrl = getPlayUrl(cdnUrl, videoUrl)
print playUrl
=========================


OSCer 都在干嘛?
发布时间:2018-02-28 来源:网络 上传者:用户
关键字: OSCer
发表文章
摘要:importrequestsimportlxmlfromlxmlimportetreedefget_content(url):try:headers={'User-Agent':'Mozilla/5.0(WindowsNT6.2;WOW64;rv:37.0)Gecko/20100101Firefox/37.0'}r=requests.get(url,headers=headers)return''+r.content.decode('utf-8')+''exceptExcep
import requests
import lxml
from lxml import etree
def get_content(url):
try:
headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.2; WOW64; rv:37.0) Gecko/20100101 Firefox/37.0'}
r = requests.get(url, headers = headers)
return '' + r.content.decode('utf-8') + ''
except Exception as exc:
#raise exc
return Noneclass User(object):
pass
def parse_content(content):
if content is None: return []
try:
xml = etree.fromstring(content)
divs= xml.findall('li/div')
page_info = []
for div in divs:
u = User()
tweets = div.findall('p')
if len(tweets) < 2:
continue
user_and_text = list(tweets[0].itertext())
u.name,u.txt = user_and_text if len(user_and_text) == 2 else [None]*2
data_comments = list(tweets[1].itertext())
u.data,u.commtents,u.client = data_comments if len(data_comments) ==3 else [None]*3
u.link = tweets[1].xpath('a')[0].get('href')
page_info.append(u)
return page_info
except Exception as exc:
raise exc
def test():
url ="http://www.oschina.net/fetch_tweets?p=40"
content = get_content(url)
infos = parse_content(content)
for u in infos:
print(u.name)
print(u.txt)
print(u.client.split('n')[1].strip() if u.client else u.client)
#print(u.name, u.txt)
if __name__ == '__main__':
test()
======================================

批量执行Linux命令或者配置
发布时间:2018-02-28 来源:网络 上传者:用户
关键字: 批量 命令 或者 执行 配置 Linux
发表文章
摘要:Python学习中,写的不好,请大家见谅。在批量服务器密码统一的情况下使用:参数介绍:-u 用户名-p 密码-P port-s 要执行的脚本-c 要执行的命令-f 要执行的服务器IP列表指定-s的时候,直接执行脚本,跳过-c#!/bin/envpythonimportparamikoimportsys,osimporttimefromoptparseimportOpti

Python学习中,写的不好,请大家见谅。在批量服务器密码统一的情况下使用:参数介绍:-u 用户名-p 密码-P port-s 要执行的脚本-c 要执行的命令-f 要执行的服务器IP列表指定-s的时候,直接执行脚本,跳过-c
#!/bin/env python
import paramiko
import sys,os
import time
from optparse import OptionParser
parser = OptionParser(add_help_option=0)
parser.add_option("-f","--file", action="store", type="string", dest="listfile",default="")
parser.add_option("-u","--user", action="store", type="string", dest="username",default="root")
parser.add_option("-p","--passwd", action="store", type="string", dest="password",default="mypass")
parser.add_option("-P","--port", action="store", type="string", dest="port",default="22")
parser.add_option("-c","--cmd", action="store", type="string", dest="cmdline",default="hostname")
parser.add_option("-s","--script", action="store", type="string", dest="script",default="")(options, args) = parser.parse_args()
listfile=options.listfile
username = options.username
passwd = options.password
port = options.port
rcmd = options.cmdline
scriptfile = options.script
time_now = time.strftime('%Y%m%d%H%M%S')infofile="log/info.txt"
if os.path.isdir("log"):
pass
else:
os.mkdir("log")
if os.path.isfile(infofile):
os.rename(infofile,infofile+time_now)
info = open(infofile,"a")
def execmd(host,port,username,passwd,rcmd):
#info = open(infofile,"a")
try:
client = paramiko.SSHClient()
#client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host,port=int(port),username=username,password=passwd,timeout=1)
#rcmd ="ifconfig eth0|grep HWaddr|awk '{print $NF}'"
print rcmd
stdin, stdout, stderr = client.exec_command(rcmd)
#info.write(host+"n"+"@"*20+"n")
for line in stdout:
info.write("%s: %s"%(host,line))
client.close()
except:
info.write("%s: SSH Login Faildnn"%(host))
#info.close()
def transfile():
try:
trans = paramiko.Transport((host,int(port)))
trans.connect(username=username,password=passwd)
sftp = paramiko.SFTPClient.from_transport(trans)
#sftp.get("","")
sftp.put(scriptfile,"/tmp/%s"%scriptfile)
trans.close()
except:
#print"File translation faild"
info.write("%s: File translation faildn"%(host))
if __name__=="__main__":
for ipaddr in open(listfile).readlines():
host = ipaddr.strip("n").rstrip().lstrip()
print host
if scriptfile =="":
pass
else:
transfile()
rcmd="sh /tmp/%s"%scriptfile
execmd(host,port,username,passwd,rcmd)
info.close()
=================================

 

posted @ 2018-10-20 10:12  三冬三夏  阅读(990)  评论(0编辑  收藏  举报