python建单抓取网页方法(python小白学习笔记一)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36411874/article/details/83650560

 

本代码使用的是python3.x

方法一:通过运行python,自动打开网页,并抓取该网页。

前提:先安装驱动,然后运行即可。详情请查看上一篇文章

import os
from selenium import webdriver

browser = webdriver.Chrome()#打开网页
browser.get("https://einvoice.taobao.com/index?&_emt=1541043729512#/online/invoice/success")
print(browser.page_source) #打印获取的内容

结果:自动弹出浏览器,并输出:

方法二:抓取到网页,保存到本地文件

先抓取文件,然后通过保存网页到本地,同时可以查看文件字节大小

import urllib.request   #导入对应的模块
#首先爬取一个网页,并抓取到内容赋值给一个变量
file=urllib.request.urlopen("https://login.taobao.com/member/login.jhtml?f=top&sub=true&redirectURL=http%3A%2F%2Feinvoice.taobao.com%2Findex%3F%26_emt%3D1541043729512")
data=file.read()
print(data)
#以写入方式打开一个本地文件,命名为 *.html等网页格式
fhandle=open('D:/爬虫/抓取文件/2018110201.html','wb')
#将1仲变量值写入该文件
fhandle.write(data)
#关闭该文件
fhandle.close()

结果:

生成文件:

方法三:使用urllib.request.urlretrieve 保存网页到本地

清除缓存,用: urllib.request.urlcleanup()

#第三种方式,抓取网页保存到本地
import urllib.request   #导入对应的模块

filename=urllib.request.urlretrieve("https://blog.csdn.net/qq_36411874/article/details/83623482",filename="D:/爬虫/抓取文件/2018110202.html")
#urlretrieve执行过程,会产生缓存,清除缓存信息,用urlcleanup()
urllib.request.urlcleanup()

方法四:使用Page

转换utf-8

from urllib import request
response = request.urlopen(r'http://python.org/') # <http.client.HTTPResponse object at 0x00000000048BC908> HTTPResponse类型
page = response.read()
page = page.decode('utf-8')
print(page)

from urllib import request和import urlib.request的区别

使用 import urllib.request 导入,使用时需要带模块名,即urllib.reuqest
使用 from urllib import request导入,使用时不需要带模块名,即直接使用request
import module 和 from module import,区别是前者所有导入的东西使用时需加上模块名,而后者则不需要。
当然也可以 import urllib.request as request 起别名的方式直接使用request

扫描二维码关注公众号,回复: 4167145 查看本文章

python能导入的有module和package,module是一个py文件,package是一堆py文件的一个特殊文件夹,urllib就属于package。

eg:

Python中from urllib import request和import urlib.request的区别:

from urllib import request
# access request directly.
mine = request()

import urllib.request
# used as urllib.request
mine = urllib.request()

调用的时候有时候为了方便用上面的第一种方式。
Python里import * 是什么意思?
import adsl,那么代码中调用的时候都是adsl.open()之类的,比如调用adsl中的foo函数(举个栗子):adsl.foo()
而from adsl import * ,可以直接用foo()。

对爬取信息进行编码和解码

import urllib.request   #导入对应的模块
print('编码结果'+urllib.request.quote("http://www.sina.com.cn"))#进行编码
print('编码结果',urllib.request.quote("http://www.sina.com.cn"))#进行编码
print("编码结果"+urllib.request.quote("http://www.sina.com.cn"))#进行编码
print("编码结果",urllib.request.quote("http://www.sina.com.cn"))#进行编码

#进行解码
print("解码结果"+urllib.request.unquote(urllib.request.quote("http://www.sina.com.cn")))

#对反爬虫网页,可以设置一些headers信息,模拟成浏览器取访问网站

逗号会有空格。详情运行

猜你喜欢

转载自blog.csdn.net/qq_36411874/article/details/83650560