Python 基础语法+简单地爬取百度贴吧内容
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个基本数据类型:
- 不可变数据(3个):数字、字符串类型、元组
- 可变数据(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 基础语法+简单地爬取百度贴吧内容的更多相关文章
- Python爬虫之简单的爬取百度贴吧数据
首先要使用的第类库有 urllib下的request 以及urllib下的parse 以及 time包 random包 之后我们定义一个名叫BaiduSpider类用来爬取信息 属性有 url: ...
- Python爬虫实战二之爬取百度贴吧帖子
大家好,上次我们实验了爬取了糗事百科的段子,那么这次我们来尝试一下爬取百度贴吧的帖子.与上一篇不同的是,这次我们需要用到文件的相关操作. 前言 亲爱的们,教程比较旧了,百度贴吧页面可能改版,可能代码不 ...
- 【学习笔记】Python 3.6模拟输入并爬取百度前10页密切相关链接
[学习笔记]Python 3.6模拟输入并爬取百度前10页密切相关链接 问题描述 通过模拟网页,实现百度搜索关键词,然后获得网页中链接的文本,与准备的文本进行比较,如果有相似之处则代表相关链接. me ...
- 转 Python爬虫实战二之爬取百度贴吧帖子
静觅 » Python爬虫实战二之爬取百度贴吧帖子 大家好,上次我们实验了爬取了糗事百科的段子,那么这次我们来尝试一下爬取百度贴吧的帖子.与上一篇不同的是,这次我们需要用到文件的相关操作. 本篇目标 ...
- java 如何爬取百度百科词条内容(java如何使用webmagic爬取百度词条)
这是老师所布置的作业 说一下我这里的爬去并非能把百度词条上的内容一字不漏的取下来(而是它分享链接的一个主要内容概括...)(他的主要内容我爬不到 也不想去研究大家有好办法可以call me) 例如 互 ...
- python简单爬虫爬取百度百科python词条网页
目标分析:目标:百度百科python词条相关词条网页 - 标题和简介 入口页:https://baike.baidu.com/item/Python/407313 URL格式: - 词条页面URL:/ ...
- Python爬虫:通过关键字爬取百度图片
使用工具:Python2.7 点我下载 scrapy框架 sublime text3 一.搭建python(Windows版本) 1.安装python2.7 ---然后在cmd当中输入python,界 ...
- 【Python数据分析】简单爬虫 爬取知乎神回复
看知乎的时候发现了一个 “如何正确地吐槽” 收藏夹,里面的一些神回复实在很搞笑,但是一页一页地看又有点麻烦,而且每次都要打开网页,于是想如果全部爬下来到一个文件里面,是不是看起来很爽,并且随时可以看到 ...
- python制作的翻译器基于爬取百度翻译【笔记思路】
#!/usr/bin/python # -*- coding: cp936 -*- ################################################### #基于百度翻 ...
随机推荐
- IONIC和Cordova安装、打包踩过的坑
1.问题1:直接执行npm install -g cordova ionic,因为网络原因,执行不成功 解决方案:将npm映射到淘宝服务器:npm install -g cnpm --registry ...
- python redis操作数据库方法
Redis redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(sorte ...
- [Mac]ssh免密登陆配置
在已经有公钥和私钥的情况下,只需要以下三步即可实现免密登陆: 1.将已有rsa公钥和私钥拷贝到~/.ssh目录下. 2.编辑配置文件:vim ~/.ssh/config,内容如下: Host xxx ...
- Fedora 10编程开发工具
1请问Fedora 10编程开发工具有什么 编辑器就用vim,编译用gcc,当然个人爱好随意 IDE的话推荐eclipse,如果做C/C++的,用codeblocks也是个不错的选择 输入gcc -v ...
- Python 深度递归
class A: pass class B(A): pass class C(A): pass class D(B, C): pass class E: pass class F(D, E): pas ...
- ngxinx 配置
vim 复制操作 1.复制 1)单行复制 在命令模式下,将光标移动到将要复制的行处,按“yy”进行复制: 2)多行复制 在命令模式下,将光标移动到将要复制的首行处,按“nyy”复制n行: 其中n为1. ...
- logging 模块 五星知识
logging 是用来记录日志的,有下面5种模式,它和print功能一样,只不过,print不能控制自己打印的内容,而logging可以控制,你想打印什么东西. logging 有两种形式: 第一种: ...
- system v共享内存与信号量综合
ipc.h #include <sys/types.h> #include <unistd.h> #include <sys/ipc.h> #include < ...
- 解决react-native软键盘弹出挡住输入框的问题
解决react-native软键盘弹出挡住输入框的问题 写登录页面,整体界面居中之后就出现软键盘弹出挡住输入框,用户体验不好的情况.用了RN官方的KeyboardAvoidingView组件,会有多出 ...
- Unity 3D Shader流水线
Unity开发VR之Vuforia 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- ...