python简单爬虫一
======简答的爬虫===========
简单的说,爬虫的意思就是根据url访问请求,然后对返回的数据进行提取,获取对自己有用的信息。然后我们可以将这些有用的信息保存到数据库或者保存到文件中。如果我们手工一个一个访问提取非常慢,所以我们需要编写程序去获取有用的信息,这也就是爬虫的作用。
一、概念:
网络爬虫,也叫网络蜘蛛(Web Spider),如果把互联网比喻成一个蜘蛛网,Spider就是一只在网上爬来爬去的蜘蛛。网络爬虫就是根据网页的地址来寻找网页的,也就是URL。举一个简单的例子,我们在浏览器的地址栏中输入的字符串就是URL,例如:https://www.baidu.com/
URL就是同意资源定位符(Uniform Resource Locator),它的一般格式如下(带方括号[]的为可选项):
protocol :// hostname[:port] / path / [;parameters][?query]#fragment
URL的格式由三部分组成:
(1)protocol:第一部分就是协议,例如百度使用的就是https协议;
(2)hostname[:port]:第二部分就是主机名(还有端口号为可选参数),一般网站默认的端口号为80,例如百度的主机名就是www.baidu.com,这个就是服务器的地址;
(3)path:第三部分就是主机资源的具体地址,如目录和文件名等。
网络爬虫就是根据这个URL来获取网页信息的。
二、简单爬虫实例
在Python3.x中,我们可以使用urlib这个组件抓取网页,urllib是一个URL处理包,这个包中集合了一些处理URL的模块,如下:
1.urllib.request模块是用来打开和读取URLs的;
2.urllib.error模块包含一些有urllib.request产生的错误,可以使用try进行捕捉处理;
3.urllib.parse模块包含了一些解析URLs的方法;
4.urllib.robotparser模块用来解析robots.txt文本文件.它提供了一个单独的RobotFileParser类,通过该类提供的can_fetch()方法测试爬虫是否可以下载一个页面。
我们使用urllib.request.urlopen()这个接口函数就可以很轻松的打开一个网站,读取并打印信息。
urlopen有一些可选参数,具体信息可以查阅Python自带的documentation。
了解到这些,我们就可以写一个最简单的程序:
# 爬虫项目
from urllib import request if __name__ == "__main__":
response = request.urlopen("http://qiaoliqiang.cn")
html = response.read()
html = html.decode("utf-8")
print(html)
结果:
E:\pythonWorkSpace\FirstProject\venv\Scripts\python.exe E:/pythonWorkSpace/FirstProject/HelloPython/reptile.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
........
上述代码有一个缺陷就是我们需要知道网站的编码格式才能正确的解析,所以我们需要改进
三、自动获取网页编码方式的方法
获取网页编码的方式有很多,个人更喜欢用第三方库的方式。
首先我们需要安装第三方库chardet,它是用来判断编码的模块,安装方法如下图所示,只需要输入指令:(或者再pycharm中的File->Settings->Project Inceptor中点击+号搜索chardet)
pip install chardet
安装好后,我们就可以使用chardet.detect()方法,判断网页的编码方式了。至此,我们就可以编写一个小程序判断网页的编码方式了。
# 爬虫项目2(自动获取)
from urllib import request
import chardet if __name__ == "__main__":
response = request.urlopen("http://qiaoliqiang.cn/")
html = response.read()
charset = chardet.detect(html)#返回的是一个字典
print(charset)#{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
html = html.decode(charset["encoding"])
print(html)
结果:
{'encoding': 'utf-8', 'confidence': 0.99, 'language': ''}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>XXXXXXXXXXX</title>
<script src="JS/jquery-1.8.3.js"></script>
...
至此实现了简单的爬虫,接下来就是提取返回的信息。也就是解析获取到的数据。
========urllib发送get请求和post请求=============
首先搭建一个后台服务器,SpringBoot项目搭建的一个小项目,在filter中获取请求的方式以及参数:
package cn.qs.filter; import java.io.IOException;
import java.util.Enumeration; import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession; import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import cn.qs.bean.user.User; /**
* 登陆过滤器
*
* @author Administrator
*
*/
@WebFilter(filterName = "loginFilter", urlPatterns = "/*")
public class LoginFilter implements Filter {
private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class); public LoginFilter() {
} public void destroy() {
} public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request;
String method = req.getMethod();
System.out.println("请求方式: " + method); Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String key = (String) parameterNames.nextElement();
System.out.println(key + " \t " + request.getParameter(key));
} response.setContentType("text/html;charset=UTF-8");
response.getWriter().write("回传中文");
} public void init(FilterConfig fConfig) throws ServletException {
} }
(1)发送一个不携带参数的get请求
from urllib import request if __name__ == "__main__":
response = request.urlopen("http://localhost:8088/login.html")
html = response.read() #解码
html = html.decode('utf-8')
print(html)
结果:
回传中文
JavaWeb控制台打印信息如下:
请求方式: GET
(2)发送一个携带参数的get请求
import urllib.request
import urllib.parse # 定义出基础网址
base_url='http://localhost:8088/login.html'
#构造一个字典参数
data_dict={
"username":"张三",
"password":"",
"utype":"",
"vcode":""
}
# 使用urlencode这个方法将字典序列化成字符串,最后和基础网址进行拼接
data_string=urllib.parse.urlencode(data_dict)
print(data_string)
new_url=base_url+"?"+data_string
response=urllib.request.urlopen(new_url)
print(response.read().decode('utf-8'))
结果:
password=13221321&utype=1&vcode=2132312&username=%E5%BC%A0%E4%B8%89
回传中文
JavaWeb控制台打印信息如下:
请求方式: GET
password 13221321
utype 1
vcode 2132312
username 张三
(3)携带参数的POST请求
import urllib.request
import urllib.parse #定义一个字典参数
data_dict={"username":"张三","password":""}
#使用urlencode将字典参数序列化成字符串
data_string=urllib.parse.urlencode(data_dict)
#将序列化后的字符串转换成二进制数据,因为post请求携带的是二进制参数
last_data=bytes(data_string,encoding='utf-8')
print(last_data) #如果给urlopen这个函数传递了data这个参数,那么它的请求方式则不是get请求,而是post请求
response=urllib.request.urlopen("http://localhost:8088/login.html",data=last_data) #我们的参数出现在form表单中,这表明是模拟了表单的提交方式,以post方式传输数据
print(response.read().decode('utf-8'))
结果:
b'password=123456&username=%E5%BC%A0%E4%B8%89'
回传中文
JavaWeb控制台打印信息如下:
请求方式: POST
password 123456
username 张三
补充:一个例子,python读取数据库,并读取url、method、param去访问请求,最后将结果记录输出到html中:
#!/usr/bin/python3
import pymysql
from urllib import request
import urllib.parse
import chardet
import json # 访问请求的方法
def requestUrl(result):
url = str(result['url']);
method = str(result['method']);
data = str(result['param']);
if url is None or method is None:
return; if data is not None:
data = str(data);
data = data.replace("form=" , ""); # 去掉form=
#数组参数处理
if data.startswith('[') and data.endswith(']'):
datas = json.loads(data);
if len(datas) > 0:
data = json.dumps(datas[0])
else :
data = '{"time": 1}';
elif "{}" == data or "" == data:
data = '{"time": 1}';
else:
data = '{"time": 1}';
try:
# POST请求
if 'POST' in method:
# 将序列化后的字符串转换成二进制数据,因为post请求携带的是二进制参数
last_data = bytes(data, encoding='utf-8');
response = urllib.request.urlopen(url, data=last_data);
responseResult = response.read().decode('utf-8')
result['responseResult'] = responseResult
else:
data_string=urllib.parse.urlencode(data);
new_url = url + "?" + data_string;
response=urllib.request.urlopen(new_url)
responseResult = response.read().decode('utf-8')
result['responseResult'] = responseResult
except Exception as e:
result['responseResult'] = "error,原因: " + str(e) # 输出爬取到的数据到本地磁盘中
def out_html(datas):
if datas is None:
return; file = open('D:\\out.html', 'w', encoding='utf-8')
file.write("<html>")
file.write(r'''
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
''');
file.write("<head>")
file.write("<title>爬取结果</title>")
# 设置表格显示边框
file.write(r'''
<style>
table{width:100%;table-layout: fixed;word-break: break-all; word-wrap: break-word;}
table td{border:1px solid black;width:300px}
</style>
''')
file.write("</head>")
file.write("<body>")
file.write("<table cellpadding='0' cellspacing='0'>")
# 遍历datas填充到表格中
for data in datas:
file.write("<tr>")
file.write("<td>%s</td>" % data['interfaceName'])
file.write('<td><a href='+str(data['url'])+'>'+str(data['url'])+'</a></td>')
file.write("<td>%s</td>" % data['method'])
file.write("<td>%s</td>" % data['param'])
file.write("<td>%s</td>" % data['responseResult'])
file.write("</tr>")
file.write("</table>")
file.write("</body>")
file.write("</html>") #主函数用法
if __name__ == '__main__':
# 打开数据库连接
db = pymysql.connect("localhost", "root", "", "pycraw")
# 使用cursor()方法获取操作游标
cursor = db.cursor(cursor = pymysql.cursors.DictCursor)
# SQL 查询语句
sql = "SELECT * FROM interface "; try:
# 执行SQL语句
cursor.execute(sql)
# 获取所有记录列表
results = cursor.fetchall() for result in results:
requestUrl(result); out_html(results);
print("处理完成")
except Exception as e:
print(e); # 关闭数据库连接
db.close()
结果:

python简单爬虫一的更多相关文章
- Python简单爬虫入门三
我们继续研究BeautifulSoup分类打印输出 Python简单爬虫入门一 Python简单爬虫入门二 前两部主要讲述我们如何用BeautifulSoup怎去抓取网页信息以及获取相应的图片标题等信 ...
- Python简单爬虫入门二
接着上一次爬虫我们继续研究BeautifulSoup Python简单爬虫入门一 上一次我们爬虫我们已经成功的爬下了网页的源代码,那么这一次我们将继续来写怎么抓去具体想要的元素 首先回顾以下我们Bea ...
- GJM : Python简单爬虫入门(二) [转载]
感谢您的阅读.喜欢的.有用的就请大哥大嫂们高抬贵手"推荐一下"吧!你的精神支持是博主强大的写作动力以及转载收藏动力.欢迎转载! 版权声明:本文原创发表于 [请点击连接前往] ,未经 ...
- Python 简单爬虫案例
Python 简单爬虫案例 import requests url = "https://www.sogou.com/web" # 封装参数 wd = input('enter a ...
- Python简单爬虫记录
为了避免自己忘了Python的爬虫相关知识和流程,下面简单的记录一下爬虫的基本要求和编程问题!! 简单了解了一下,爬虫的方法很多,我简单的使用了已经做好的库requests来获取网页信息和Beauti ...
- Python简单爬虫
爬虫简介 自动抓取互联网信息的程序 从一个词条的URL访问到所有相关词条的URL,并提取出有价值的数据 价值:互联网的数据为我所用 简单爬虫架构 实现爬虫,需要从以下几个方面考虑 爬虫调度端:启动爬虫 ...
- python 简单爬虫(beatifulsoup)
---恢复内容开始--- python爬虫学习从0开始 第一次学习了python语法,迫不及待的来开始python的项目.首先接触了爬虫,是一个简单爬虫.个人感觉python非常简洁,相比起java或 ...
- python 简单爬虫diy
简单爬虫直接diy, 复杂的用scrapy import urllib2 import re from bs4 import BeautifulSoap req = urllib2.Request(u ...
- Python简单爬虫入门一
为大家介绍一个简单的爬虫工具BeautifulSoup BeautifulSoup拥有强大的解析网页及查找元素的功能本次测试环境为python3.4(由于python2.7编码格式问题) 此工具在搜索 ...
随机推荐
- redis 入手
redis是数据库,数据库肯定是处理处理数据.既然是处理数据,无非就是增删查改 redis用于操作键的命令基本上分为两大类 对任何键都可执行的: DEL 命令. EXPIRE 命令. RENAME 命 ...
- WebClient的使用
1.下载网页源码: private void button1_Click(object sender, EventArgs e) { string url = textBox1.Text; strin ...
- CSS自适应导航菜单
以下是一个简单实例,可以通过学习了解响应工菜单的制作. html <nav class="nav"> <ul> <li class="cur ...
- Css实现拖动效果
效果如下,可以拖动滑块,数字显示的是离左侧距离:
- 秒杀多线程之CyclicBarrier
CyclicBarrier是用来一个关卡来阻挡住所有线程,等所有线程全部执行到关卡处时,再统一执行下一步操作. package com.multithread.cyclicbarrier; impor ...
- 题解 P5015 【标题统计】
既然这个题这么水 大家不如来盘点一下算法呗 首先说一个事:逗号表达式 这玩意的值是最后一个表达式的值 那么我们就可以愉快的放进循环条件里摩擦 话说这个应该是基础吧,大多数代码都可以这样干 具体可以后面 ...
- [洛谷P4341][BJWC2010]外星联络
题目大意:给你一个长度为$n(n\leqslant3\times10^3)$的字符串,要你求出其中出现次数大于$1$的子串,并按字典序输出次数. 题解:建$SAM$后求出每个点的$size$,最后按字 ...
- 【BZOJ1416/1498】【NOI2006】神奇的口袋(数论,概率)
[BZOJ1416/1498][NOI2006]神奇的口袋(数论,概率) 题面 BZOJ1416 BZOJ1498 洛谷 题面都是图片形式是什么鬼.. 题解 考虑以下性质 1.\(x[1],x[2]. ...
- 电子商务(电销)平台中财务模块(Finance)数据库设计明细
以下是自己在电子商务系统设计中的数据库设计经验总结,而今发表出来一起分享,如有不当,欢迎跟帖讨论~ 资金账户表 (finance_account)|-- 自动编号|-- 用户编号|-- 预付款 (ad ...
- [转]从头开始 GAN
1 前言 GAN的火爆想必大家都很清楚了,各种GAN像雨后春笋一样冒出来,大家也都可以名正言顺的说脏话了[微笑脸].虽然目前GAN的酷炫应用还集中在图像生成上,但是GAN也已经拓展到NLP,Robot ...