Python爬虫技术3:获取数据
b站学习:https://www.bilibili.com/video/BV12E411A7ZQ
一、补充urllib的知识
使用httpbin.org网站帮助我们检查
注意:以下代码要import urllib.request(有些没复制上来)
1.get
import urllib.request
#获取一个get请求
response=urllib.request.urlopen("http://www.baidu.com")
print(response.read().decode('utf-8')) #会获取到的网页源码进行解码
把得到的结果放入一个新建的html文件中就可以用浏览器打开该网页
response=urllib.request.urlopen("http://httpbin.org/get")
print(response.read().decode('utf-8'))
2.post
import urllib.request
#获取一个post请求
import urllib.parse
data=bytes(urllib.parse.urlencode({
"hello":"world"}),encoding="utf-8") #封装成字节文件
response=urllib.request.urlopen("http://httpbin.org/post",data=data)
print(response.read().decode("utf-8"))
模拟结果:
在httpbin.org网站上看到的结果:
3.超时处理
防止爬虫的网页相应失败而停滞不前
#超时处理(异常处理)
try:
response=urllib.request.urlopen("http://httpbin.org/get",timeout=0.01)
print(response.read().decode('utf-8'))
except urllib.error.URLError as e:
print("timeout!")
response=urllib.request.urlopen("http://douban.com")
# print(response.status)
print(response.getheaders())
#response不仅可以返回请求的网页信息,还可以查看一些头部等等响应信息
response=urllib.request.urlopen("http://www.baidu.com")
print(response.getheaders())
print(response.getheader("Server"))
4.伪装自己
从上面的结果可以看到,模拟的User-agent与真实的浏览器的User-agent是不一样的,因此会被识破,所以我们接下来要伪装自己,达到与浏览器真实的响应一样的结果。
例子1:使用post访问httpbin.org
import urllib.parse
url="http://httpbin.org/post"
headers={
#伪装自己
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36"
}
data=bytes(urllib.parse.urlencode({
"name":"vivian"}),encoding="utf-8")
req=urllib.request.Request(url=url,data=data,headers=headers,method="POST") #被我们封装的请求对象
response=urllib.request.urlopen(req)
print(response.read().decode("utf-8"))
import urllib.parse
url="https://douban.com"
headers={
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.106 Safari/537.36"
}
req=urllib.request.Request(url=url,headers=headers)
response=urllib.request.urlopen(req)
print(response.read().decode("utf-8"))
#-*- coding = utf-8 -*-
#@Time : 2020/9/8 23:17
#@Author : Vivian
#@File : spider.py
#@Sofeware : PyCharm
from bs4 import BeautifulSoup #网页解析,获取数据
import re #正则表达式,进行文件匹配
import urllib.request,urllib.error #指定URL,获取网页数据
import xlwt #进行excel操作
import sqlite3 #进行SQLite数据库操作
def main():
baseurl="https://movie.douban.com/top250?start="
#1.爬取网页
datalist=getData(baseurl)
savepath=".\\豆瓣电影Top250.xls"
#3.保存数据
#saveData(savepath)
askURL("https://movie.douban.com/top250?start=0")
#爬取网页
def getData(baseurl):
datalist=[]
for i in range(0,10): #调用获取页面信息的函数:十次
url=baseurl+str(i*25)
html=askURL(url) #保存获取到的网页源码
# 2.逐一解析数据
return datalist
#得到指定一个URL的网页内容
def askURL(url):
head={
#模拟浏览器头部信息向豆瓣服务器发送消息 注意空格去掉
"User-Agent": "Mozilla / 5.0(Windows NT 10.0;Win64;x64) AppleWebKit / 537.36(KHTML, likeGecko) Chrome / 80.0.3987.106Safari / 537.36"
}
#用户代理:告诉豆瓣服务器我们是什么类型的机器(浏览器)(表示我们可以接收什么水平的文件内容)
request=urllib.request.Request(url,headers=head)
html=""
try:
response=urllib.request.urlopen(request)
html=response.read().decode("utf-8")
print(html)
except urllib.error.URLError as e:
if hasattr(e,"code"):
print(e.code)
if hasattr(e,"reason"):
print(e.reason)
return html
#保存数据
def saveData(savepath):
pass
if __name__ == "__main__": #当程序执行时(入口)
#调用函数
main()