Python笔记

1、Python3和Pycharm2018的安装

2、Python3基础语法

2.1.1、数据类型

2.1.1.1、数据类型:数字(整数和浮点数)

整数:int类型

浮点数:float类型。

2.1.1.2、数据类型:字符类型
2.1.1.3、数据类型:布尔类型

True:真

Flase:假

2.1.1.3、数据类型:列表(list)
>>> l =['aaa','bbb','ccc']
>>> l[0]
'aaa'
>>> l.append('ddd') # 追加元素
>>> l
['aaa', 'bbb', 'ccc', 'ddd']
>>> l.pop() #数组尾部移除元素
'ddd'
>>> l
['aaa', 'bbb', 'ccc']
>>> l.pop(1) #指定索引位置移除元素
'bbb'
>>> l
['aaa', 'ccc']
>>>
2.1.1.4、数据类型:元组(tuple)

元组和list类似,但是它是不能修改

2.1.1.5、数据类型:字典(dictionary)

类似java的map

>>> m = {'name':'test1','age':18}
>>> m
{'name': 'test1', 'age': 18}
>>> m['name']
'test1'
>>> m['name']='test2'
>>> m
{'name': 'test2', 'age': 18}
>>> m[name] # 如果键不存在报错
Traceback (most recent call last):
File "<pyshell#17>", line 1, in <module>
m[name]
NameError: name 'name' is not defined
>>>
2.1.1.6、数据类型:集合(set)

set和dict类似,也是一组key的集合,但不存储value,key不能重复.

>>> s = set([1,2,3])
>>> s
{1, 2, 3}
>>> list = list(s) # 将set类型转换为list类型
>>> list
[1, 2, 3]
>>> s.add(4)
>>> s
{1, 2, 3, 4}
>>> s.remove(2)
>>> s
{1, 3, 4}
>>>
2.1.1.7、数据类型:None

类似于java的null

2.1.2、变量

python的变量是动态语言,java是静态语言。

// java
int a=1; //a的数字是int类型
a="abc"; //报错
a=1       //当前a的数据类型是整数
a=1.0 //浮点型
a='abc' //字符型
常量

python习惯性以大写定义变量,认为是一个常量,但是python中没有办法去约束你不可以修改这个值。

变量:不可变和可变

python3里的6个基本数据类型:

  1. 不可变数据(3个):数字、字符串类型、元组
  2. 可变数据(3个):数组、字典、集合
>>> a='abc'
>>> b=a
>>> a='123'
>>> a
'123'
>>> b
'abc'

2.1.3、运算符

2.1.3.1、算术运算符

+、-、*、/、%

>>> 7/2
3.5
>>> 6/2
3.0
>>> 7//2
3
>>> 7%2
1
>>> 7.0/2
3.5
>>> 7.0//2 #取整的值取决于相除的2方
3.0
>>> 5 ** 2 # 用** 表示计算幂乘方
25
>>> a='123'
>>> b = a*3 # 将a的值复制3次
>>> b
'123123123'
>>>
2.1.3.2、关系运算符
2.1.3.3、赋值运算符
2.1.3.4、逻辑运算符

and:且

or:或

not:取反

2.1.3.5、位运算符
2.1.3.6、成员运算符
>>> list = [1,2,3,4,5]
>>> a=2
>>> a in list # 判断a是否在指定序列中
True
>>> b=10
>>> b in list
False
>>> b not in list # 使用not in 判断是否不在指定的序列中
True

2.1.4、流程语句

2.1.4.1、条件判断
if 5>3:
print(1)
elif 5>7:
print(2)
#... elif可以写0到多个
else: # else也可以省略
#code
2.1.4.2、循环
>>> a =1
>>> while a<=10:
print(a)
a++ # python不支持 SyntaxError: invalid syntax
>>> while a<=10:
print(a)
a+=1
1
2
3
4
5
6
7
8
9
10 >>> for n in range(5):
print(n) 0
1
2
3
4
>>> for n in range(1,10):
print(n) 1
2
3
4
5
6
7
8
9

3、爬百度贴吧

1、获取第一页的html

from urllib import request, parse

# 获取每一页的html
def loadPage(url):
# 1、创建连接对象
req = request.Request(url)
# 2、创建连接并获得响应对象
response = request.urlopen(req)
# 3、读取响应的内容
html = response.read()
print(type(html)) # bytes类型的数字,不是str
print('html:', html)
# 4、将读取的内容解码
content = html.decode('utf-8')
print('content:', content) if __name__ == '__main__':
url = 'https://tieba.baidu.com/f?ie=utf-8&kw=%E6%9D%8E%E6%AF%85'
loadPage(url)

2、将下载的内容写入到文件中

from urllib import request, parse

# 获取每一页的html
def loadPage(url):
# 1、创建连接对象
req = request.Request(url)
# 2、创建连接并获得响应对象
response = request.urlopen(req)
# 3、读取响应的内容
html = response.read()
print(type(html)) # bytes类型的数字,不是str
print('html:', html)
# 4、将读取的内容解码
content = html.decode('utf-8')
print('content:', content)
return content # 将下载的内容写入到文件中
def writeFile(html, filename):
print('正在保存:' + filename)
f = open(filename, 'w', encoding='utf-8') # open()用来读或写文件:读:mode='r',写:mode='w'
f.write(html)
f.close() if __name__ == '__main__':
# 获取每一页的html
url = 'https://tieba.baidu.com/f?ie=utf-8&kw=%E6%9D%8E%E6%AF%85'
content = loadPage(url)
# 将下载的内容写入到文件中
filename = 'D:/course/tmp/test1.html'
writeFile(content, filename)
print('程序结束...')

3、设置起始页和终止页

int():将str转换为int类型

float():将str转换为float类型

str():将转换为str字符串类型

from urllib import request, parse

# 获取每一页的html
def loadPage(url):
# 1、创建连接对象
req = request.Request(url)
# 2、创建连接并获得响应对象
response = request.urlopen(req)
# 3、读取响应的内容
html = response.read()
print(type(html)) # bytes类型的数字,不是str
print('html:', html)
# 4、将读取的内容解码
content = html.decode('utf-8')
print('content:', content)
return content # 将下载的内容写入到文件中
def writeFile(html, filename):
print('正在保存:' + filename)
f = open(filename, 'w', encoding='utf-8') # open()用来读或写文件:读:mode='r',写:mode='w'
f.write(html)
f.close() # 设置起始页和终止页
def tiebaSpider(url, beginPage, endPage):
for page in range(beginPage, endPage+1):
pn = (page-1) * 50 # 设置pn的值
new_url = url + '&pn=' + str(pn) # 生成新的url
# print('new_url: ', new_url)
print('new_url %s' % new_url)
# print('new_url %s, %s' %(new_url, new_url))
filename = '第'+str(page)+'页.html' # 生成下载要保存的文件名
html = loadPage(new_url) # 获得下载页面的内容
writeFile(html, filename) # 写入文件 if __name__ == '__main__':
# 获取每一页的html
url = 'https://tieba.baidu.com/f?ie=utf-8&kw=%E6%9D%8E%E6%AF%85'
beginPage = int(input('请输入起始页:')) # 输入默认的是str类型
endPage = int(input('请输入终止页:'))
print('beginPage: %d , endPage:%d' %(beginPage, endPage))
tiebaSpider(url, beginPage, endPage)
print('程序结束...')

4、爬取贴吧图片

4.1、先要获得下载图片的链接地址
# 获得图片的链接地址
def loadPage2(url):
# 创建连接对象
req = request.Request(url)
# 创建url连接获得响应对象
response = request.urlopen(req)
# 读取网页的内容
html = response.read()
# 对内容解码
html = html.decode('utf-8')
# 对内容创建dom树对象
content = etree.HTML(html)
print(type(content)) # <class 'lxml.etree._Element'>
# 通过 xpath规则获取满足条件的数据
link_list = content.xpath('//div[@id="post_content_102822382749"]/img/@src')
# link_list = content.xpath('//div[@id="post_content_102822382749"]/a/text()')
for link in link_list:
print(link) # 图片的链接地址 if __name__ == '__main__':
url = 'https://tieba.baidu.com/p/4946204416'
loadPage2(url)
4.2、将图片下载到本地保存
from urllib import request, parse
from lxml import etree # 获取每一页的html
def loadPage(url):
# 1、创建连接对象
req = request.Request(url)
# 2、创建连接并获得响应对象
response = request.urlopen(req)
# 3、读取响应的内容
html = response.read()
print(type(html)) # bytes类型的数字,不是str
print('html:', html) # 内容本身就是图片的内容,图片的内容由二进制组成,不需要解码
return html # 获得图片的链接地址
def loadPage2(url):
# 创建连接对象
req = request.Request(url)
# 创建url连接获得响应对象
response = request.urlopen(req)
# 读取网页的内容
html = response.read()
# 对内容解码
html = html.decode('utf-8')
# 对内容创建dom树对象
content = etree.HTML(html)
print(type(content)) # <class 'lxml.etree._Element'>
# 通过 xpath规则获取满足条件的数据
link_list = content.xpath('//div[@id="post_content_102822382749"]/img/@src')
# link_list = content.xpath('//div[@id="post_content_102822382749"]/a/text()')
for link in link_list:
print(link) # 图片的链接地址
filename = link[-20:]
print('正在保存文件:' + filename)
# 将图片写入到文件中
# mode='w':写的数据类型是str
# 写入二进制内容需要设置mode='wb',并且不需要设置encoding='utf-8'
# 使用with就不需要 手动f.close()
with open('D:/course/tmp/'+filename, 'wb') as f:
html1 = loadPage(link)
f.write(html1) # f = open('D:/course/tmp/'+, 'w', encoding='utf-8') # open()用来读或写文件:读:mode='r',写:mode='w'
# f.write(html)
# f.close() if __name__ == '__main__':
url = 'https://tieba.baidu.com/p/4946204416'
loadPage2(url)

Python 基础语法+简单地爬取百度贴吧内容的更多相关文章

  1. Python爬虫之简单的爬取百度贴吧数据

    首先要使用的第类库有 urllib下的request  以及urllib下的parse  以及 time包  random包 之后我们定义一个名叫BaiduSpider类用来爬取信息 属性有 url: ...

  2. Python爬虫实战二之爬取百度贴吧帖子

    大家好,上次我们实验了爬取了糗事百科的段子,那么这次我们来尝试一下爬取百度贴吧的帖子.与上一篇不同的是,这次我们需要用到文件的相关操作. 前言 亲爱的们,教程比较旧了,百度贴吧页面可能改版,可能代码不 ...

  3. 【学习笔记】Python 3.6模拟输入并爬取百度前10页密切相关链接

    [学习笔记]Python 3.6模拟输入并爬取百度前10页密切相关链接 问题描述 通过模拟网页,实现百度搜索关键词,然后获得网页中链接的文本,与准备的文本进行比较,如果有相似之处则代表相关链接. me ...

  4. 转 Python爬虫实战二之爬取百度贴吧帖子

    静觅 » Python爬虫实战二之爬取百度贴吧帖子 大家好,上次我们实验了爬取了糗事百科的段子,那么这次我们来尝试一下爬取百度贴吧的帖子.与上一篇不同的是,这次我们需要用到文件的相关操作. 本篇目标 ...

  5. java 如何爬取百度百科词条内容(java如何使用webmagic爬取百度词条)

    这是老师所布置的作业 说一下我这里的爬去并非能把百度词条上的内容一字不漏的取下来(而是它分享链接的一个主要内容概括...)(他的主要内容我爬不到 也不想去研究大家有好办法可以call me) 例如 互 ...

  6. python简单爬虫爬取百度百科python词条网页

    目标分析:目标:百度百科python词条相关词条网页 - 标题和简介 入口页:https://baike.baidu.com/item/Python/407313 URL格式: - 词条页面URL:/ ...

  7. Python爬虫:通过关键字爬取百度图片

    使用工具:Python2.7 点我下载 scrapy框架 sublime text3 一.搭建python(Windows版本) 1.安装python2.7 ---然后在cmd当中输入python,界 ...

  8. 【Python数据分析】简单爬虫 爬取知乎神回复

    看知乎的时候发现了一个 “如何正确地吐槽” 收藏夹,里面的一些神回复实在很搞笑,但是一页一页地看又有点麻烦,而且每次都要打开网页,于是想如果全部爬下来到一个文件里面,是不是看起来很爽,并且随时可以看到 ...

  9. python制作的翻译器基于爬取百度翻译【笔记思路】

    #!/usr/bin/python # -*- coding: cp936 -*- ################################################### #基于百度翻 ...

随机推荐

  1. kbmMW随机数与强密码

    kbmMW随机数生成器 为了使基于kbmMW开发的项目更安全,其又提供了随机数及强密码生成实现类,拿来即用,让人感觉真是站到巨人的肩膀上好干活! 随机数方面,kbmMW分别提供32及64位的随机数生成 ...

  2. idea本地安装 lombok插件

    转:https://blog.csdn.net/weixin_41404773/article/details/80689639 idea本地安装 lombok插件 项目中经常使用bean,entit ...

  3. Python 依赖关系

    class Person: def play(self, tools): # 通过参数的传递把另外一个类的对象传递进来 tools.run() print("很开心, 我能玩儿游戏了&quo ...

  4. Coach Said No Worry

    I have been losing memories those days. I can't get through what I was doing right then. I have prom ...

  5. [译]TensorFlow入门

    TensorFlow入门 张量(tensor) Tensorflow中的主要数据单元是张量(tensor), 一个张量包含了一组基本数据,可以是列多维数据.一个张量的"等级"(ra ...

  6. [转]lua元表代码分析

    http://lin-style.iteye.com/blog/1012138 版本整理日期:2011/4/21 元表其实就是可以让你HOOK掉一些操作的一张表. 表的定义在ltm.h/c的文件里.对 ...

  7. 读懂TCP状态转移

    读懂TCP状态转移过程,对理解网络编程颇有帮助,本文将对TCP状态转移过程进行介绍,但各状态(总共11个)含义不在本文介绍的范围,请参考文末的书目列表. TCP状态转换图(state transiti ...

  8. 计时器---JS

    <script type="text/javascript"> function count(){ var a=document.getElementById(&quo ...

  9. [LeetCode&Python] Problem 485. Max Consecutive Ones

    Given a binary array, find the maximum number of consecutive 1s in this array. Example 1: Input: [1, ...

  10. Gym 102091A: Flying Squirrel(RMQ)

    题意:如图,有N个柱子,每次我可以从高柱子X到低柱子Y,而且需要满足中间的柱子都小于X的高度. 思路:现在有Q次询问,每次给定(X,Y),(如果ht[X]<ht[Y],则交换XY),问X为起点, ...