python怎么爬取网页数据,python爬取网页数据步骤

大家好,给大家分享一下python爬取网页数据表格会超出索引,很多人还不知道这一点。下面详细解释一下。现在让我们来看看!

本篇文章给大家谈谈笨方法学Python3进阶版有限状态机,以及笨方法学Python读后感1500字,希望对各位有所帮助,不要忘了收藏本站喔python源码库

习题16:读写文件

代码
from sys import argv  #从sys包导入入模块argv
,filename = argv #解包,赋值两个参数,脚本名词和文件名称
print(f"We're going to erase {filename}") #打印一段格式化字符串
print("If you don't want that , hit CTRL-C (^C).") #打印字符串
print("If you do want that , hit RETURN")  #打印字符串

input("?")  #输出提示信息‘?’,接收输入的内容
print("Opening the file...")  #输出字符串
target = open(filename,"w")
#用open函数打开我们输入的文件名,模式为写模式,并且将文件放入变量target
print("Truncating the file. Goodbye!") #打印字符串

target.truncate()  #在变量target后调用truncate函数清空文件
print("Now I'm going to ask your for three lines.") #打印字符串
line1 = input("line1:") #接收用户输入的字符串
line2 = input("line2:") #接收用户输入的字符串
line3 = input("line3:") #接收用户输入的字符串

print("I'm going to write these to the file.") #输出字符串
target.write(line1+"\n"+line2+"\n"+line3+"\n") #用加号连接

print("And finally,We close it.") #输出字符串
target.close()  #在变量target后调用close函数,保存文件

PS C:\Users\WU\pyfile> python  
We're going to erase 
If you don't want that , hit CTRL-C (^C).
If you do want that , hit RETURN
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask your for three lines.
line1:666
line2:6666
line3:66666
I'm going to write these to the file.
And finally,We close it.
from sys import argv
,filename = argv
a = open(filename)
print(a.read())
PS C:\Users\WU\pyfile> python  
666
6666
66666

·

知识点

与文件相关的命令(方法/函数)今天我们的操作系统和文件系统已经模糊了随机访问存储和磁盘之间的界限,但我们依然在用旧时磁带的磁头读写的思路来操作文件python编程代码看不懂怎么办。命令行输入 python -m pydoc open 查看open()函数的说明。 ‘m’模式打开文件本身就具有清空文件的作用,所以前面就不需要target.truncate()函数。 w只是一个字符的特殊字符串,用来表示文件的访问模式,此外还有’r’表示读取(read),’a’表示追加(append)等。open 对于文件的写入操作态度是安全第一,所以你只有特别指定以后,它才会进行写入操作因为open()默认是’r’,即读取文本模式,不能进行写入; 所以需要指定写入模式, 用到参数w。

open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise OSError upon failure.
      ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    'r'       open for reading (default)
    'w'       open for writing, truncating the file first
    'x'       create a new file and open it for writing
    'a'       open for writing, appending to the end of the file if it exists
    'b'       binary mode
    't'       text mode (default)
    '+'       open a disk file for updating (reading and writing)
    'U'       universal newline mode (deprecated)
    ========= ===============================================================

‘+’是一个修饰符号,可以用来实现‘w+’,’r+’和‘a+’。这样可以把文件用同时读和写的方法打开,并根据使用的字符,以不一样的方式实现文件的定位。

破坏程序

破坏程序一:输入文件名错误

PS C:\Users\WU\pyfile> python  
Traceback (most recent call last):
  File "C:\Users\WU\pyfile\", line 3, in <module>
    a = open(filename)
FileNotFoundError: [Errno 2] No such file or directory: ''

习题17:更多文件操作

代码
from sys import argv
from  import exists
,from_file,to_file = argv
print(f"Copying from {from_file} to {to_file}.")
#we could do these two on one line,how?
in_file = open(from_file,"r",encoding='utf-8',errors='ignore') #处理解码失败问题
indata = ()
print(f"Does the output file exist?{exists(to_file)}")
#将文件名字符串作为参数,如果文件存在,返回True,否则返回False
print(f"Ready, hit RETRUN to continue,CTRL^C to abort.")
input()
out_file = open(to_file,'w')
out_file.write(indata)
print("Alright,all done")
out_file.close()
in_file.close()
from sys import argv
,from_file,to_file = argv
indata = open(from_file).read()
out_file = open(to_file,"w")
out_file.write(indata)
out_file.close()
print(open(to_file).read())
from sys import argv
,from_file,to_file = argv
open(to_file,"w").write(open(from_file).read())
print(open(to_file).read())
PS C:\Users\WU\pyfile> python   
Copying from  to 
The input file is 15 bytes long
Ready , hit RETURN to continue,CTRK-C to abort

Alright , all done.
知识点

import是用来导入代码中需要用到的特性所在的模块的,from…import…是从某个模块中提取我们所要用到的特性的。close函数作用是关闭文件并保存,释放资源。out_file = open(to_file, ‘w’) 执行时会创建 to_file 文件,但是没内容 。out_file.write(indata) 执行时,内容会写入到 to_file 的内存数据中,但仍未写入硬盘。只有在执行 close 时 python 才指定文本的各种操作已经结束了,不会再有任何变化,这个时候在写入硬盘可以尽可能地减少硬盘读写操作,提高效率。如果不close,那就得等垃圾回收时,自动释放资源。但垃圾回收的时机是不确定无法控制的。特别是程序是一个服务,需要很长时间才能执行完,或者很大并发执行,就很有可能导致资源被耗尽,甚至导致死锁。使用了中的exists模块拉判断文件是否存在。若文件存在。将返回True;否则返回函数以数值形式返回传递的字符串的长度indata = open(from_file).read,在到达脚本结尾的时候,无需再运行in_file.close()。因为read()一旦运行,文件就会被python关掉。cat 最大的用途是答应文件内容到屏幕上

破坏程序

程序破坏一:计算机内部解码错误,不是故意的,我也很迷茫了很久。

PS C:\Users\WLS\Zedstudy> python   
Copying from  to .
Traceback (most recent call last):
  File "", line 8, in <module>
    indata = ()
UnicodeDecodeError: 'gbk' codec can't decode byte 0xff in position 0: illegal multibyte sequence

错误的意思是:Unicode的解码(Decode)出现错误(Error)了,以gbk编码的方式去解码(该字符串变成Unicode),但是此处通过gbk的方式,却无法解码(can’t decode )。“illegal multibyte sequence”意思是非法的多字节序列,即没法(解码)了。 此种错误,可能是要处理的字符串本身不是gbk编码,但是却以gbk编码去解码 。比如,字符串本身是utf-8的,但是却用gbk去解码utf-8的字符串,所以结果不用说,则必然出错。所以最终改成

in_file = open(from_file,"r",encoding='utf-8',errors='ignore')

rb和 r原文链接UnicodeDecodeError: 'gbk’怎么破?Python 读写文件的编码与解码问题

习题18:命名、变量、代码和函数

#this one is like your s with argv
def print_two(*args):
    arg1,arg2 = args #将参数解包
    print(f"arg1:{arg1},arg2={arg2}")
    #冒号以下,使用4个空格缩进的行都属于print_tow 函数的内容。
#ok,that *args is actually pointless, we can just do this
def print_two_again(arg1,arg2):
    print(f"arg1:{arg1},arg2={arg2}")
    #可以省略解包的过程,直接使用()内的名称作为变量名。
#this just take one argument.接受一个参数。
def print_one(arg1):
    print(f"arg1:{arg1}")
#this one takes no arguments.函数可以不接受任何参数。
def print_none():
    print("I got nothing")
print_two("Zed","Shaw")
print_two_again("Zed","Shaw")
print_one("First!")
print_none()
PS C:\Users\WU\pyfile> python 
arg1:Zed,arg2=Shaw
arg1:Zed,arg2=Shaw
arg1:First!
I got nothing
知识点

函数可以同时接受多个参数,类似argv;也可以只接受一个参数;也可以不接收任何参数。函数作用 给代码段命名,就更变量给字符串和数值命名一样。可以接受参数,就跟你的脚本接受argv一样。利用以上两点,可以让你创建“迷你脚本”或者“小命令”。更加学术点来讲,函数是一种功能函数,是为了减低编程和代码重用。

Python使用def保留字定义一个函数,语法形式如下:
Def<函数名>(<参数列表>):
<函数体>
Return <返回值列表>

巩固练习

函数定义是以def开始的。函数名由字母,下划线,数字组成,但数字不可在开头,函数名最好体现函数的功能。与变量名的书写规则一样。函数名称不是紧跟着括号 (,也可以有空格。括号里可以包含参数也可以不包含参数。多个参数必须用逗号,隔开。不能使用重复的参数名。参数后紧跟 “():” ,这是格式。记住函数名那一行最后是个冒号“:”。函数定义后的代码一定要四个空格的缩进。不能多不能少。在函数结束的位置取消缩进

运行函数、调用函数和使用函数是同一个意思。

破坏程序

破坏程序一:变量命名。

def print_two_again(ari1,arg2):
    print(f"arg1:{arg1},arg2={arg2}")
PS C:\Users\WU\pyfile> python 
arg1:Zed,arg2=Shaw
Traceback (most recent call last):
  File "C:\Users\WU\pyfile\", line 21, in <module>
    print_two_again("Zed","Shaw")
  File "C:\Users\WU\pyfile\", line 9, in print_two_again
    print(f"arg1:{arg1},arg2={arg2}")
NameError: name 'arg1' is not defined

习题19:函数和变量

代码
#定义一个名为cheese_and_crackers的函数,带有两个参数
def cheese_and_crackers(cheese_count, box_of_crackers):
    print(f"You have {cheese_count} cheeses!") #打印格式化字符串
    print(f"You have {box_of_crackers} boxes of crackers")
    print(f"Man that's enough for party") #打印字符串
    print("Get a blanket. \n") #打印字符串,并且换行
#打印语句和传递两个数字给函数
print("We can just give the function numbers directly:") #打印字符串
cheese_and_crackers(20,30) #调用函数。参数形式为数值

#打印语句和定义两个变量
print("Or, we can use variables from our :")  #打印字符串
amount_of_cheese = 10 #赋值变量
amount_of_crackers = 50 #赋值变量
cheese_and_crackers(amount_of_cheese, amount_of_crackers)
#调用函数,参数形式为变量

print("We can even do more inside too:") #打印语句
cheese_and_crackers(10+20,5+6)#调用函数,参数形式为数学表达式

print("And we can combine the two, variable and math:") #打印语句
cheese_and_crackers(amount_of_cheese+10, amount_of_crackers+1000)
#调用函数,参数形式为变量和数学表达式
PS C:\Users\WU\pyfile> python 
We can just give the function numbers directly:
You have 20 cheeses!
You have 30 boxes of crackers
Man that's enough for party
Get a blanket.

Or, we can use variables from our :
You have 10 cheeses!
You have 50 boxes of crackers
Man that's enough for party
Get a blanket.

We can even do more inside too:
You have 30 cheeses!
You have 11 boxes of crackers
Man that's enough for party
Get a blanket.

And we can combine the two, variable and math:
You have 20 cheeses!
You have 1050 boxes of crackers
Man that's enough for party
Get a blanket.
知识点

函数里的变量和脚本里的变量是没有联系的。一个程序中的变量包括两类:全局变量和局部变量。全局变量指在函数之外定义的变量,一般没有缩进,在程序全过程有效。局部变量指在函数内部使用的变量,仅在函数内部有效,当函数退出时变量将不存在(被释放掉了)。我们可以直接给函数传递数字,也可以是变量,还可以给它数学表达式,深圳数学表达式和变量组合起来用。函数的参数和生成变量时用的变量时用的 = 与赋值符类似。事实上,如果一个物体可以用 = 对其命名,通常也可以将其作为参数传递给一个函数。函数的参数个数的限制数量取决于Python的版本和所用的操作系统,不过就算有限制,限制也是很大的。不过实际应用终,5个参数已经不少了,再多就令人头疼。

习题20:函数和文件

代码
from sys import argv #从sys导入argv
,input_file = argv #解包,把用户输入的信息放入变量中

def print_all(f):
    print(f.read())  #定义函数,输出文件f的内容
def rewind(f):
    f.seek(0)  #定义函数,把f文件的地址指针指向文件起始位置
def print_a_line(line_count,f):
    print(line_count , f.readline(),end="")
    #创建函数,输出文件中第line_count行的内容,end是为了不换行。
    #readline()函数返回的内容中包含文件本来就有\n,而print在打印时又会添加一个\n。

current_file = open(input_file) #把input_file变量文件传递给current_file变量
print("Fisrt let's print the whole file:\n") #打印字符串
print_all(current_file) #调用函数,读取全部文件

print("Now let's rewind, kind of like a tape.")  #打印字符串
rewind(current_file) #调用函数,将文件指针重新指向文件起始位置

print("Let's print three lines:") #打印字符串
current_line = 1  #赋值
print_a_line(current_line,current_file) #调用函数,打印第一行,指针记录当前位置
current_line += 1 #赋值
print_a_line(current_line,current_file) #调用函数,打印第二行,指针记录当前位置
current_line += 1 #赋值
print_a_line(current_line,current_file) #调用函数,打印第三行,指针记录当前位置
PS C:\Users\WU\pyfile> python  
Fisrt let's print the whole file:

666
6666
66666

Now let's rewind, kind of like a tape.
Let's print three lines:
1 666
3 6666
5 66666
知识点

file.readline()读取文件的一行,然后将“指针”移动到\n的后面,文件会记录每次调用readline()后的读取位置,这样下次被调用时读取接下来的一行。(0)是重新定位在文件的第0位即开始位置。python中File seek()的用法

作用:移动文件读取指针到指定位置。
语法:(offset,[whence])
   offset -- 开始的偏移量,也就是代表需要移动偏移的字节数
   whence:可选,默认值为 0。给offset参数一个定义,表示要从哪个位置开始偏移;
   0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。
         (1)f.seek(p,0)  移动当文件开头第p个字节处,绝对位置。
        (2)f.seek(p,1)  移动到当前位置之后的第p个字节。
        (3)f.seek(p,2)  移动到文件结尾之后的第p个字节。
seek() 无返回值,故值为None。 
eek()函数的处理对象是字节而非行。

所有二元数学操作符(+、-、、/、//整数商、%模运算、**次幂 )都有与之对应的增强赋值操作符(+=、-=、=、/=、//=、%=、**=)。 例如 x+=y 等价于 x=x+y。增强赋值操作符简化代码的表达。readline()函数返回的内容中包含文件本来就有\n,而print在打印时又会添加一个\n,这样假如文本中本来有换行,那么打印就会出现多一个空行,即间隔行。解决方法是在print()函数中多加一个参数end=””,这样print就不会为每一行多打印\n出来。

破坏程序

破坏程序一:变量不在函数内部。应当在函数内定义 end=""

current_line = 1  #赋值
print_a_line(current_line,current_file,end="") 
PS C:\Users\WU\pyfile> python  
Fisrt let's print the whole file:

666
6666
66666
Now let's rewind, kind of like a tape.
Let's print three lines:
Traceback (most recent call last):
  File "C:\Users\WU\pyfile\", line 22, in <module>
    print_a_line(current_line,current_file,end="") #调用函数,打印第一行,指针记录当前位置
TypeError: print_a_line() got an unexpected keyword argument 'end'
  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值