Python是我比较喜欢的语言,莫名的喜欢,对Python的学习可能起初是敲错了网址开始的,哈哈哈~

工作的任务从一个网站后台做登录、爬取数据,写入服务器Redis中,同事认为我会用PHP来写,哼!让你猜到那该多没意思,于是乎有了如下Python的代码,你看50多行搞定了。

 #!/usr/bin/python3
import requests
import re
import redis
from pyquery import PyQuery as pq loginUrl = 'https://manage.xxx.com.cn/home/login'
userName = 'xxx'
passWord = 'xxx' redisServer = '192.168.0.2'
redisPort = 6379
redisPass = '' productList = {'椰油':'CL_Spot','咖啡':'COFFEE','工业铜':'COPPER'}
volumeList = {'CL_Spot':[0, 0], 'COFFEE':[0, 0], 'COPPER':[0, 0]} def main():
jsessionid = getCookie()
doLogin(jsessionid)
dataUrl = 'https://manage.xxx.cn/?pageNo=1&pageSize=100'
cookies = {'JSESSIONID': jsessionid}
r = requests.get(dataUrl, cookies = cookies)
dom = pq(r.text)
lines = dom('table').eq(1).find('tr').items()
for line in lines:
line = re.sub(r'<!--.*-->', '', str(line))
pattern = re.compile(r'<td>(.*?)</td>')
group = pattern.findall(line)
if not group:
continue
productCode = productList[group[3]]
if group[6] == '买':
volumeList[productCode][0]+= int(group[7]) * int(group[8])
if group[6] == '卖':
volumeList[productCode][1]+= int(group[7]) * int(group[8]) redisClient = redis.Redis(host=redisServer, port=redisPort, password=redisPass)
for x in volumeList:
keyUp = 'redis_order_count_u_%s' % x
keyDown = 'redis_order_count_d_%s' % x
redisClient.set(keyUp, int(volumeList[x][0]))
redisClient.set(keyDown, int(volumeList[x][1])) def getCookie():
ua = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36'}
r = requests.get(loginUrl, headers = ua)
return r.cookies['JSESSIONID'] def doLogin(jsessionid):
param = {'userName': userName, 'password': passWord}
cookies = {'JSESSIONID': jsessionid}
requests.post(loginUrl, data = param, cookies = cookies) if __name__ == '__main__':
main()

另一个服务也需要这个需求,用了最近看的Golang来实现一次,瞧写了100多行

 package main

 import (
"fmt"
"net/http"
"net/url"
"os"
"strings"
"strconv"
"gopkg.in/redis.v4"
"github.com/PuerkitoBio/goquery"
) var loginUrl string = "https://manage.xxx.com.cn/home/login"
var dataUrl string = "https://manage.xxx.com.cn/?pageNo=1&pageSize=100"
var userName string = "xxx"
var passWord string = "xxx"
var redisServer string = "192.168.1.2"
var redisPort string = ""
var redisPass string = ""
var redisDB int = 0 func main() {
productList := make(map[string] string)
productList["椰油"] = "CL_Spot"
productList["咖啡"] = "COFFEE"
productList["工业铜"] = "COPPER"
volumeList := make(map[string] int)
volumeList["u_CL_Spot"] = 0
volumeList["d_CL_Spot"] = 0
volumeList["u_COFFEE"] = 0
volumeList["d_COFFEE"] = 0
volumeList["u_COPPER"] = 0
volumeList["d_COPPER"] = 0
jsessionid := getCookie()
doLogin(jsessionid) request, err := http.NewRequest("GET", dataUrl, nil)
request.AddCookie(&http.Cookie{Name: "JSESSIONID", Value: jsessionid})
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
defer response.Body.Close()
doc, err := goquery.NewDocumentFromReader(response.Body)
doc.Find("table").Eq(1).Find("tr").Each(func(i int, tr *goquery.Selection) {
td := tr.Find("td")
name := td.Eq(3).Text()
dir := td.Eq(6).Text()
if val, ok := productList[name]; ok {
buyNum, _ := strconv.Atoi(td.Eq(7).Text())
buyUnit, _ := strconv.Atoi(td.Eq(8).Text())
num := buyNum * buyUnit
cacheKey := ""
if dir == "买" {
cacheKey = fmt.Sprintf("u_%s", val)
} else if dir == "卖" {
cacheKey = fmt.Sprintf("d_%s", val)
}
volumeList[cacheKey] += num
}
})
redisClient := redis.NewClient(&redis.Options{
Addr: fmt.Sprintf("%s:%s", redisServer, redisPort),
Password: redisPass,
DB: redisDB,
})
for k, v := range volumeList {
strKey := fmt.Sprintf("redis_order_count_%s", k)
redisClient.Set(strKey, int(v), 0)
}
fmt.Println("puti volume get success")
} func getCookie() string {
jsessionid := ""
response, err := http.Get(loginUrl)
if err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
defer response.Body.Close()
for _, val := range response.Cookies() {
if val.Name == "JSESSIONID" {
jsessionid = val.Value
}
}
return jsessionid
} func doLogin(jsessionid string) bool {
data := url.Values{}
data.Set("userName", userName)
data.Add("password", passWord)
request, _ := http.NewRequest("POST", loginUrl, strings.NewReader(data.Encode()))
request.Header.Add("Content-Type", "application/x-www-form-urlencoded")
request.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))
request.AddCookie(&http.Cookie{Name: "JSESSIONID", Value: jsessionid})
client := &http.Client{}
response, err := client.Do(request)
if err != nil {
fmt.Println(err.Error())
os.Exit(0)
}
defer response.Body.Close()
return true
}

Python的实现到上线半天的功夫搞定了,Go足足搞了1整天,蹩脚的语法与不熟悉的语法让我学习了很多知识点,最后Mac编译到Linux上执行也给我上了一课。

觉得入门学习这两门语言挺好,一个是脚本语言另一个是编译语言,用处都很广泛。轩轩你准备好了吗?

比较爬虫用的语言Python与Go的更多相关文章

  1. golang学习笔记17 爬虫技术路线图,python,java,nodejs,go语言,scrapy主流框架介绍

    golang学习笔记17 爬虫技术路线图,python,java,nodejs,go语言,scrapy主流框架介绍 go语言爬虫框架:gocolly/colly,goquery,colly,chrom ...

  2. 【Python】【爬虫】如何学习Python爬虫?

    如何学习Python爬虫[入门篇]? 路人甲 1 年前 想写这么一篇文章,但是知乎社区爬虫大神很多,光是整理他们的答案就够我这篇文章的内容了.对于我个人来说我更喜欢那种非常实用的教程,这种教程对于想直 ...

  3. 深入浅出爬虫之道: Python、Golang与GraphQuery的对比

    深入浅出爬虫之道: Python.Golang与GraphQuery的对比 本文将分别使用 Python ,Golang 以及 GraphQuery 来解析某网站的 素材详情页面 ,这个页面的特色是具 ...

  4. Python爬虫之小试牛刀——使用Python抓取百度街景图像

    之前用.Net做过一些自动化爬虫程序,听大牛们说使用python来写爬虫更便捷,按捺不住抽空试了一把,使用Python抓取百度街景影像. 这两天,武汉迎来了一个德国总理默克尔这位大人物,又刷了一把武汉 ...

  5. 基于scrapy爬虫的天气数据采集(python)

    基于scrapy爬虫的天气数据采集(python) 一.实验介绍 1.1. 知识点 本节实验中将学习和实践以下知识点: Python基本语法 Scrapy框架 爬虫的概念 二.实验效果 三.项目实战 ...

  6. python人工智能爬虫系列:怎么查看python版本_电脑计算机编程入门教程自学

    首发于:python人工智能爬虫系列:怎么查看python版本_电脑计算机编程入门教程自学 http://jianma123.com/viewthread.aardio?threadid=431 本文 ...

  7. 决策树ID3原理及R语言python代码实现(西瓜书)

    决策树ID3原理及R语言python代码实现(西瓜书) 摘要: 决策树是机器学习中一种非常常见的分类与回归方法,可以认为是if-else结构的规则.分类决策树是由节点和有向边组成的树形结构,节点表示特 ...

  8. 浅谈爬虫 《一》 ===python

    浅谈爬虫 <一> ===python  ‘’正文之前先啰嗦一下,准确来说,在下还只是一个刚入门IT世界的菜鸟,工作近两年了,之前做前端的时候就想写博客来着,现在都转做python了,如果还 ...

  9. 标准爬虫初探,来自Python之父的大餐!

    首先不得不承认自己做了标题党.本文实质是分析500lines or less的crawlproject,这个project的地址是https://github.com/aosabook/500line ...

随机推荐

  1. python:更改pip源

    windows更改pip源 cmd echo %APPDATA% 打开目录 创建文件夹pip 创建pip.ini文件 [global] timeout = 60 index-url = http:// ...

  2. MySQL数据库的sql语句的导出与导入

    1.MySQL数据库的导出 (1)选择对应的数据库 (2)点击右键选择Dump SQL File (3)会出现保存框,选择保存的位置,名称不建议重新起名 (4)点击保存出现 (5)点击Close就可以 ...

  3. 测试框架Unitest的运行原理,以及多个测试类中的执行顺序以及简化方法

    单元测试单元测试(unit testing)是指对软件中的最小可测试单元进行检查和验证.对于单元测试中单元的含义,一般来说,要根据实际情况去判定其具体含义,如C语言中单元指一个函数,Java里单元指一 ...

  4. Ubuntu 远程 Jupyter 配置

    Ubuntu 远程 Jupyter 配置 每次上课都要重新部署环境,最近看到阿里云的大学生优惠活动,就着手了一台云服务器,于是就把环境部署在上面了. 环境:阿里云 Ubuntu 16.04 64位 新 ...

  5. SQLAlchemy 增删改查 一对多 多对多

    1.创建数据表 # ORM中的数据表是什么呢? # Object Relation Mapping # Object - Table 通过 Object 去操纵数据表 # 从而引出了我们的第一步创建数 ...

  6. 洛谷 P3376 【【模板】网络最大流】

    题目描述 如题,给出一个网络图,以及其源点和汇点,求出其网络最大流. 输入 第一行包含四个正整数N.M.S.T,分别表示点的个数.有向边的个数.源点序号.汇点序号. 接下来M行每行包含三个正整数ui. ...

  7. webpack学习笔记 (二) html-webpack-plugin使用

    这个插件的两个作用: 为html文件中引入的外部资源如script.link动态添加每次compile后的hash,防止引用缓存的外部文件问题 可以生成创建html入口文件,比如单页面可以生成一个ht ...

  8. Mock.js——数据模板定义

    1. 安装 npm install mockjs --save-dev //安装开发依赖 2. 数据模板定义规则 Mock.mock({...}) String: 'string|num1-num2' ...

  9. mac常用操作

    Command+Shift+. 可以显示隐藏文件.文件夹 touch a.txt 新建txt文件

  10. 关于a标签的用法总结

    onclick的事件被先执行 ,其次是href中定义的(页面跳转或者javascript) 同时存在两个定义的时候(onclick与href都定义了),如果想阻止href的动作,在onclick必须加 ...