2025年3月6日 星期四 甲辰(龙)年 月初五 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > Python

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

时间:08-23来源:作者:点击数:32

本代码使用的是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://www.cdsy.xyz/computer/programme/Python/230823/cd45620.html",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

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信息,模拟成浏览器取访问网站

逗号会有空格。详情运行

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门