1.Requests简介

Requests是一款目前非常流行的http请求库,使用python编写,能非常方便的对网页Requests进行爬取,也是爬虫最常用的发起请求第三方库。

安装方法

pip install requests

或者conda安装

conda install requests
1、re.status_code 响应的HTTP状态码

2、re.text 响应内容的字符串形式

3、re.content 响应内容的二进制形式

4、re.encoding 响应内容的编码

1.1访问百度

试一试对百度首页进行数据请求:

项目难度:⭐

import requests
import requests
# 发出http请求
re=requests.get("https://www.baidu.com")
# 查看响应状态
print(re.status_code)
#输出:200
#200就是响应的状态码,表示请求成功
#我们可以通过res.status_code的值来判断请求是否成功。
200
re.text
'<!DOCTYPE html>\r\n<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=https://ss1.bdstatic.com/5eN1bjq8AAUYm2zgoY3K/r/www/cache/bdorz/baidu.min.css><title>ç\x99¾åº¦ä¸\x80ä¸\x8bï¼\x8cä½\xa0å°±ç\x9f¥é\x81\x93</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus=autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=ç\x99¾åº¦ä¸\x80ä¸\x8b class="bg s_btn" autofocus></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ\x96°é\x97»</a> <a href=https://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>å\x9c°å\x9b¾</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>è§\x86é¢\x91</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>è´´å\x90§</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>ç\x99»å½\x95</a> </noscript> <script>document.write(\'<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u=\'+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ \'" name="tj_login" class="lb">ç\x99»å½\x95</a>\');\r\n                </script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">æ\x9b´å¤\x9a产å\x93\x81</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å\x85³äº\x8eç\x99¾åº¦</a> <a href=http://ir.baidu.com>About Baidu</a> </p> <p id=cp>&copy;2017&nbsp;Baidu&nbsp;<a href=http://www.baidu.com/duty/>使ç\x94¨ç\x99¾åº¦å\x89\x8då¿\x85读</a>&nbsp; <a href=http://jianyi.baidu.com/ class=cp-feedback>æ\x84\x8fè§\x81å\x8f\x8dé¦\x88</a>&nbsp;京ICPè¯\x81030173å\x8f·&nbsp; <img src=//www.baidu.com/img/gs.gif> </p> </div> </div> </div> </body> </html>\r\n'

1.2下载txt文件

例:用爬虫下载孔乙己的文章,网址是https://apiv3.shanbay.com/codetime/articles/mnvdu

我们打开这个网址 可以看到是鲁迅的文章

我们尝试着用爬虫保存文章的内容

项目难度:⭐

re = requests.get('https://apiv3.shanbay.com/codetime/articles/mnvdu')
# 查看页面响应状态
print("页面响应状态:",re.status_code)
页面响应状态: 200
with open('鲁迅文章.txt', 'w') as file:# 将数据的字符串形式写入文件中print('正在爬取小说')file.write(re.text)
正在爬取小说
file
#re.txt就是网页中的内容,将内容保存到txt文件中
<_io.TextIOWrapper name='鲁迅文章.txt' mode='w' encoding='cp936'>
re.encoding
'UTF-8'

1.3下载图片

re.text用于文本内容的获取、下载

re.content用于图片、视频、音频等内容的获取、下载

项目难度:⭐⭐

re = requests.get('https://img-blog.csdnimg.cn/20210424184053989.PNG')
with open('datawhale.png','wb') as picture:# 将数据的二进制形式写入文件中picture.write(re.content)

re.encoding 爬取内容的编码形似,常见的编码方式有 ASCII、GBK、UTF-8 等。如果用和文件编码不同的方式去解码,我们就会得到一些乱码。

2.HTML解析和提取

浏览器工作原理:

向浏览器中输入某个网址,浏览器回向服务器发出请求,然后服务器就会作出响应。其实,服务器返回给浏览器的这个结果就是HTML代码,浏览器会根据这个HTML代码将网页解析成平时我们看到的那样

res = requests.get('https://baidu.com')
print(res.text)
<!DOCTYPE html>
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>ç™¾åº¦ä¸€ä¸‹ï¼Œä½ å°±çŸ¥é“</title></head> <body link=#0000cc> <div id=wrapper> <div id=head> <div class=head_wrapper> <div class=s_form> <div class=s_form_wrapper> <div id=lg> <img hidefocus=true src=//www.baidu.com/img/bd_logo1.png width=270 height=129> </div> <form id=form name=f action=//www.baidu.com/s class=fm> <input type=hidden name=bdorz_come value=1> <input type=hidden name=ie value=utf-8> <input type=hidden name=f value=8> <input type=hidden name=rsv_bp value=1> <input type=hidden name=rsv_idx value=1> <input type=hidden name=tn value=baidu><span class="bg s_ipt_wr"><input id=kw name=wd class=s_ipt value maxlength=255 autocomplete=off autofocus></span><span class="bg s_btn_wr"><input type=submit id=su value=百度一下 class="bg s_btn"></span> </form> </div> </div> <div id=u1> <a href=http://news.baidu.com name=tj_trnews class=mnav>æ–°é—»</a> <a href=http://www.hao123.com name=tj_trhao123 class=mnav>hao123</a> <a href=http://map.baidu.com name=tj_trmap class=mnav>地图</a> <a href=http://v.baidu.com name=tj_trvideo class=mnav>视频</a> <a href=http://tieba.baidu.com name=tj_trtieba class=mnav>贴吧</a> <noscript> <a href=http://www.baidu.com/bdorz/login.gif?login&amp;tpl=mn&amp;u=http%3A%2F%2Fwww.baidu.com%2f%3fbdorz_come%3d1 name=tj_login class=lb>登录</a> </noscript> <script>document.write('<a href="http://www.baidu.com/bdorz/login.gif?login&tpl=mn&u='+ encodeURIComponent(window.location.href+ (window.location.search === "" ? "?" : "&")+ "bdorz_come=1")+ '" name="tj_login" class="lb">登录</a>');</script> <a href=//www.baidu.com/more/ name=tj_briicon class=bri style="display: block;">更多产品</a> </div> </div> </div> <div id=ftCon> <div id=ftConw> <p id=lh> <a href=http://home.baidu.com>å

³äºŽç™¾åº¦ About Baidu

©2017 Baidu ä½¿ç”¨ç™¾åº¦å‰å¿
读  意见反馈 äº¬ICP证030173号 

**HTML(Hyper Text Markup Language)**是一种超文本标记语言,是由一堆标记组成。

我的网页 Hello,World # 3.BeautifulSoup简介

我们一般会使用BeautifulSoup这个第三方库

安装方法:
pip install bs4

conda install bs4
我们来解析豆瓣读书 Top250

它的网址是:https://book.douban.com/top250

项目难度:⭐⭐

re = requests.get("https://book.douban.com/top250")
re.status_code
418
import io
import sys
import requests
from bs4 import BeautifulSoup
headers = {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36'
}
res = requests.get('https://book.douban.com/top250', headers=headers)
with open("豆瓣html.txt","w") as file:file.write(res.text,encoding='gb18030')
---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-35-f3d05a807223> in <module>1 with open("豆瓣html.txt","w") as file:
----> 2     file.write(res.text,encoding='gb18030')TypeError: write() takes no keyword arguments
soup = BeautifulSoup(res.text, 'lxml')
print(soup.find('a'))
<a class="nav-login" href="https://accounts.douban.com/passport/login?source=book" rel="nofollow">登录/注册</a>

python 打印信息时会有限制 我们将打印的编码改成gb18030

headers表示我们的请求网页的头,对于没有headers的请求可能会被服务器判定为爬虫而拒绝提供服务

通过 from bs4 import BeautifulSoup 语句导入 BeautifulSoup

然后使用 BeautifulSoup(res.text, lxmlr’) 语句将网页源代码的字符串形式解析成了 BeautifulSoup 对象

解析成了 BeautifulSoup 对象可以较为方便的提取我们需要的信息

那么如何提取信息呢?

BeautifulSoup 为我们提供了一些方法

find()方法和find_all()方法:

find() 返回符合条件的首个数据
find_all() 返回符合条件的所有**数据

除了传入 HTML 标签名称外,BeautifulSoup 还支持熟悉的定位

# 定位div开头 同时id为'doubanapp-tip的标签
soup.find('div', id='doubanapp-tip')
<div id="doubanapp-tip">
<a class="tip-link" href="https://www.douban.com/doubanapp/app?channel=qipao">豆瓣 <span class="version">6.0</span> 全新发布</a>
<a class="tip-close" href="javascript: void 0;">×</a>
</div>
# 定位a抬头 同时class为rating_nums的标签
soup.find_all('p', class_='pl')
#class是python中定义类的关键字,因此用class_表示HTML中的class
[<p class="pl">[清] 曹雪芹 著 / 人民文学出版社 / 1996-12 / 59.70元</p>,<p class="pl">余华 / 作家出版社 / 2012-8-1 / 20.00元</p>,<p class="pl">[哥伦比亚] 加西亚·马尔克斯 / 范晔 / 南海出版公司 / 2011-6 / 39.50元</p>,<p class="pl">[英] 乔治·奥威尔 / 刘绍铭 / 北京十月文艺出版社 / 2010-4-1 / 28.00</p>,<p class="pl">[美国] 玛格丽特·米切尔 / 李美华 / 译林出版社 / 2000-9 / 40.00元</p>,<p class="pl">刘慈欣 / 重庆出版社 / 2012-1-1 / 168.00元</p>,<p class="pl">[明] 罗贯中 / 人民文学出版社 / 1998-05 / 39.50元</p>,<p class="pl">林奕含 / 北京联合出版公司 / 2018-2 / 45.00元</p>,<p class="pl">[日] 东野圭吾 / 刘姿君 / 南海出版公司 / 2013-1-1 / 39.50元</p>,<p class="pl">[英] 乔治·奥威尔 / 荣如德 / 上海译文出版社 / 2007-3 / 10.00元</p>,<p class="pl">[英] 阿·柯南道尔 / 丁钟华 等 / 群众出版社 / 1981-8 / 53.00元/68.00元</p>,<p class="pl">[法] 圣埃克苏佩里 / 马振聘 / 人民文学出版社 / 2003-8 / 22.00元</p>,<p class="pl">金庸 / 生活·读书·新知三联书店 / 1994-5 / 96.00元</p>,<p class="pl">三毛 / 哈尔滨出版社 / 2003-8 / 15.80元</p>,<p class="pl">(丹麦)安徒生 / 叶君健 / 人民文学出版社 / 1997-08 / 25.00元</p>,<p class="pl">路遥 / 人民文学出版社 / 2005-1 / 64.00元</p>,<p class="pl">[法] 阿尔贝·加缪 / 柳鸣九 / 上海译文出版社 / 2010-8 / 22.00元</p>,<p class="pl">钱锺书 / 人民文学出版社 / 1991-2 / 19.00</p>,<p class="pl">王小波 / 中国青年出版社 / 1997-10 / 27.00元</p>,<p class="pl">当年明月 / 中国海关出版社 / 2009-4 / 358.20元</p>,<p class="pl">[哥伦比亚] 加西亚·马尔克斯 / 杨玲 / 南海出版公司 / 2012-9-1 / 39.50元</p>,<p class="pl">[美] 乔治·R. R. 马丁 / 谭光磊 / 重庆出版社 / 2005-5 / 68.00元</p>,<p class="pl">J.K.罗琳 (J.K.Rowling) / 苏农 / 人民文学出版社 / 2008-12-1 / 498.00元</p>,<p class="pl">[美] 哈珀·李 / 高红梅 / 译林出版社 / 2012-9 / 32.00元</p>,<p class="pl">[以色列] 尤瓦尔·赫拉利 / 林俊宏 / 中信出版社 / 2014-11 / 68.00元</p>]

4.实践项目1:自如公寓数据抓取

日前 , 国务院办公厅印发《关于加快培育和发展住房租赁市场的若干意见》,你是某新媒体公司的一名员工,老板希望对武汉的租房情况进行深度调研与分析,你想调查自如公寓的数据情况。根据工作的安排,你调研的是自如公寓武汉房屋出租分析的任务。

项目难度:⭐⭐⭐⭐

自如公寓官网:https://wh.ziroom.com/z/z/
通过观察官网你发现

第1页的网页为:https://wh.ziroom.com/z/p1/

第2页的网页为:https://wh.ziroom.com/z/p2/

第3页的网页为:https://wh.ziroom.com/z/p3/

第50页的网页为:https://wh.ziroom.com/z/p50/

你继续观察,发现

房屋的信息网页为类似于:https://wh.ziroom.com/x/741955798.html

即:https://wh.ziroom.com/x/XXXX.html

因此你有了思路,通过访问自如公寓的网站,获取每个房间后面的数字号 然后通过数字号访问房屋的直接信息,然后抓取房屋的信息保存在excel中

于是你访问了房屋的网页:https://wh.ziroom.com/x/741955798.html

通过观察房屋的网页,你发现是这些信息是你需要的

房屋的名称,房屋的面积,房屋的朝向,房屋的户型,房屋的位置,房屋的楼层,是否有电梯,房屋的年代,门锁情况,绿化情况

但是你遇到了困难,不知道这些信息的标签信息,不能用beautifulsoup对他们进行定位

通过百度查询,浏览器按F12时能进入源代码模式 或者 点击右键进入审查元素

点击左上角的箭头,可以定位到元素的位置

方法掌握后你开始写代码了

import requests
from bs4 import BeautifulSoup
import random
import time
import csv

写到这里的时候,你想到,我多次访问自如的官网,如果只用一个UA头岂不是很容易被反爬虫识别

你想到,我可以做很多个UA头,然后每次访问的时候可以随机选一个,想到这里,你直呼自己是个天才

于是,你到网上找到了很多UA头信息

#这里增加了很多user_agent
#能一定程度能保护爬虫
user_agent = ["Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50","Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0","Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3; rv:11.0) like Gecko","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1","Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1","Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11","Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)"]

现在开始正式开始爬取数据了

房屋的名称,房屋的价格,房屋的面积,房屋的朝向,房屋的户型,房屋的位置,房屋的楼层,是否有电梯,房屋的年代,门锁情况,绿化情况

你思考爬取的信息应该保存到csv文件中,于是你导入了csv包 并简单的了解了CSV包的用法

第一步,是要获取房屋的数字标签

于是你打开了自如的官网,用浏览器的元素进行定位

发现房屋的信息标签都是这个
< a href=“dd//wh.ziroom.com/x/741955798.html” target="_blank"> 房屋名称< /a >
聪明的你,随手写下了这个代码,便能爬取自如前50页

random.choice(user_agent)
'Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)'
def get_info():csvheader=['名称','面积','朝向','户型','位置','楼层','是否有电梯','建成时间',' 门锁','绿化']with open('wuhan_ziru.csv', 'a+', newline='') as csvfile:writer  = csv.writer(csvfile)writer.writerow(csvheader)for i in range(1,10):  #总共有50页print('正在爬取自如第%s页'%i)timelist=[1,2,3]print('有点累了,需要休息一下啦(¬㉨¬)')time.sleep(random.choice(timelist))   #休息1-3秒,防止给对方服务器过大的压力!!!url='https://wh.ziroom.com/z/p%s/'%iheaders = {'User-Agent': random.choice(user_agent)}r = requests.get(url, headers=headers)r.encoding = r.apparent_encodingsoup = BeautifulSoup(r.text, 'lxml')all_info = soup.find_all('div', class_='info-box')print('开始干活咯(๑>؂<๑)')for info in all_info:href = info.find('a')if href !=None:href='https:'+href['href']try:print('正在爬取%s'%href)house_info=get_house_info(href)writer.writerow(house_info)except:print('出错啦,%s进不去啦( •̥́ ˍ •̀ू )'%href)
def get_house_info(href):#得到房屋的信息time.sleep(1)headers = {'User-Agent': random.choice(user_agent)}response = requests.get(url=href, headers=headers)response=response.content.decode('utf-8', 'ignore')soup = BeautifulSoup(response, 'lxml')name = soup.find('h1', class_='Z_name').textsinfo=soup.find('div', class_='Z_home_b clearfix').find_all('dd')area=sinfo[0].textorien=sinfo[1].textarea_type=sinfo[2].textdinfo=soup.find('ul',class_='Z_home_o').find_all('li')location=dinfo[0].find('span',class_='va').textloucen=dinfo[1].find('span',class_='va').textdianti=dinfo[2].find('span',class_='va').textniandai=dinfo[3].find('span',class_='va').textmensuo=dinfo[4].find('span',class_='va').textlvhua=dinfo[5].find('span',class_='va').text['名称','面积','朝向','户型','位置','楼层','是否有电梯','建成时间',' 门锁','绿化']room_info=[name,area,orien,area_type,location,loucen,dianti,niandai,mensuo,lvhua]return room_info

4.1步骤拆分

csvheader=['名称','面积','朝向','户型','位置','楼层','是否有电梯','建成时间',' 门锁','绿化']
with open('wuhan_ziru.csv', 'a+', newline='') as csvfile:writer  = csv.writer(csvfile)writer.writerow(csvheader)
re = requests.get("https://wh.ziroom.com/z/p1/")
re.status_code
200
# print('正在爬取自如第%s页'%i)
i = 1
timelist=[1,2,3]
print('有点累了,需要休息一下啦(¬㉨¬)')
# time.sleep(random.choice(timelist))   #休息1-3秒,防止给对方服务器过大的压力!!!
url='https://wh.ziroom.com/z/p%s/'%i
headers = {'User-Agent': random.choice(user_agent)}
r = requests.get(url, headers=headers)
r.encoding = r.apparent_encoding
soup = BeautifulSoup(r.text, 'lxml')
soup_info = soup.find_all('h5', class_='title turn')
print(soup_info)
有点累了,需要休息一下啦(¬㉨¬)
[<h5 class="title turn"><a href="//wh.ziroom.com/x/807988393.html" target="_blank">合租·纽宾凯公园里4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/807827295.html" target="_blank">合租·凯乐桂园3居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/807953610.html" target="_blank">合租·纽宾凯公园里4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/808037785.html" target="_blank">合租·保利华都3居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/807919198.html" target="_blank">合租·常青花园十一小区4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/793749918.html" target="_blank">合租·汇悦天地4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/767210815.html" target="_blank">合租·星星新城3居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/789408295.html" target="_blank">合租·国创光谷上城5居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/768041620.html" target="_blank">合租·千禧城5居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/795938432.html" target="_blank">合租·千家鑫苑3居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/807753018.html" target="_blank">合租·琨瑜府5居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/807215719.html" target="_blank">合租·汉口新界广场5居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/807853636.html" target="_blank">合租·光明上海公馆5居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/779302932.html" target="_blank">合租·惠东花园4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/765812075.html" target="_blank">合租·金地国际花园5居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/807251426.html" target="_blank">合租·电建地产盛世江城3居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/807979615.html" target="_blank">合租·万科金域时代4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/785748194.html" target="_blank">合租·统建新干线4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/745251276.html" target="_blank">合租·磨山港湾4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/807917147.html" target="_blank">合租·圆梦美丽家园4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/793643315.html" target="_blank">合租·新地盛世东方4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/790675697.html" target="_blank">合租·当代国际花园三期4居室-南卧</a></h5>, <h5 class="title turn"><a href="//wh.ziroom.com/x/807995540.html" target="_blank">合租·兴华尚都国际3居室-南卧</a></h5>]
for info_list in soup_info:href = info_list.find('a')print(href)
<a href="//wh.ziroom.com/x/807988393.html" target="_blank">合租·纽宾凯公园里4居室-南卧</a>
<a href="//wh.ziroom.com/x/807827295.html" target="_blank">合租·凯乐桂园3居室-南卧</a>
<a href="//wh.ziroom.com/x/807953610.html" target="_blank">合租·纽宾凯公园里4居室-南卧</a>
<a href="//wh.ziroom.com/x/808037785.html" target="_blank">合租·保利华都3居室-南卧</a>
<a href="//wh.ziroom.com/x/807919198.html" target="_blank">合租·常青花园十一小区4居室-南卧</a>
<a href="//wh.ziroom.com/x/793749918.html" target="_blank">合租·汇悦天地4居室-南卧</a>
<a href="//wh.ziroom.com/x/767210815.html" target="_blank">合租·星星新城3居室-南卧</a>
<a href="//wh.ziroom.com/x/789408295.html" target="_blank">合租·国创光谷上城5居室-南卧</a>
<a href="//wh.ziroom.com/x/768041620.html" target="_blank">合租·千禧城5居室-南卧</a>
<a href="//wh.ziroom.com/x/795938432.html" target="_blank">合租·千家鑫苑3居室-南卧</a>
<a href="//wh.ziroom.com/x/807753018.html" target="_blank">合租·琨瑜府5居室-南卧</a>
<a href="//wh.ziroom.com/x/807215719.html" target="_blank">合租·汉口新界广场5居室-南卧</a>
<a href="//wh.ziroom.com/x/807853636.html" target="_blank">合租·光明上海公馆5居室-南卧</a>
<a href="//wh.ziroom.com/x/779302932.html" target="_blank">合租·惠东花园4居室-南卧</a>
<a href="//wh.ziroom.com/x/765812075.html" target="_blank">合租·金地国际花园5居室-南卧</a>
<a href="//wh.ziroom.com/x/807251426.html" target="_blank">合租·电建地产盛世江城3居室-南卧</a>
<a href="//wh.ziroom.com/x/807979615.html" target="_blank">合租·万科金域时代4居室-南卧</a>
<a href="//wh.ziroom.com/x/785748194.html" target="_blank">合租·统建新干线4居室-南卧</a>
<a href="//wh.ziroom.com/x/745251276.html" target="_blank">合租·磨山港湾4居室-南卧</a>
<a href="//wh.ziroom.com/x/807917147.html" target="_blank">合租·圆梦美丽家园4居室-南卧</a>
<a href="//wh.ziroom.com/x/793643315.html" target="_blank">合租·新地盛世东方4居室-南卧</a>
<a href="//wh.ziroom.com/x/790675697.html" target="_blank">合租·当代国际花园三期4居室-南卧</a>
<a href="//wh.ziroom.com/x/807995540.html" target="_blank">合租·兴华尚都国际3居室-南卧</a>
href['href']
'//wh.ziroom.com/x/807995540.html'
for info_list in soup_info:href = info_list.find('a')if href !=None:href='https:'+href['href']try:print('正在爬取%s'%href)except:pass
正在爬取https://wh.ziroom.com/x/807988393.html
正在爬取https://wh.ziroom.com/x/807827295.html
正在爬取https://wh.ziroom.com/x/807953610.html
正在爬取https://wh.ziroom.com/x/808037785.html
正在爬取https://wh.ziroom.com/x/807919198.html
正在爬取https://wh.ziroom.com/x/793749918.html
正在爬取https://wh.ziroom.com/x/767210815.html
正在爬取https://wh.ziroom.com/x/789408295.html
正在爬取https://wh.ziroom.com/x/768041620.html
正在爬取https://wh.ziroom.com/x/795938432.html
正在爬取https://wh.ziroom.com/x/807753018.html
正在爬取https://wh.ziroom.com/x/807215719.html
正在爬取https://wh.ziroom.com/x/807853636.html
正在爬取https://wh.ziroom.com/x/779302932.html
正在爬取https://wh.ziroom.com/x/765812075.html
正在爬取https://wh.ziroom.com/x/807251426.html
正在爬取https://wh.ziroom.com/x/807979615.html
正在爬取https://wh.ziroom.com/x/785748194.html
正在爬取https://wh.ziroom.com/x/745251276.html
正在爬取https://wh.ziroom.com/x/807917147.html
正在爬取https://wh.ziroom.com/x/793643315.html
正在爬取https://wh.ziroom.com/x/790675697.html
正在爬取https://wh.ziroom.com/x/807995540.html
href
'https://wh.ziroom.com/x/807995540.html'
headers = {'User-Agent': random.choice(user_agent)}
response = requests.get(url=href, headers=headers)
response.status_code
200
response.content.decode
<function bytes.decode(encoding='utf-8', errors='strict')>
response=response.content.decode('utf-8', 'ignore')
response.content.decode
---------------------------------------------------------------------------AttributeError                            Traceback (most recent call last)<ipython-input-145-8942591645b2> in <module>
----> 1 response.content.decodeAttributeError: 'str' object has no attribute 'content'
soup = BeautifulSoup(response, 'lxml')

4.2 soup.find的两种解析

soup.find('h1',class_='Z_name')
<h1 class="Z_name"><i class="status iconicon_turn"></i>自如友家·兴华尚都国际·3居室-01卧</h1>
soup.find_all('h1',class_='Z_name')
[<h1 class="Z_name"><i class="status iconicon_turn"></i>自如友家·兴华尚都国际·3居室-01卧</h1>]
soup.find('h1',class_='Z_name').text

'自如友家·兴华尚都国际·3居室-01卧'
soup.find_all('h1',class_='Z_name')[0].text
'自如友家·兴华尚都国际·3居室-01卧'
soup.find_all('div',class_='Z_home_b clearfix')[0].find_all('dd')[0]
<dd>15.4㎡</dd>
soup.find_all('div',class_='Z_home_b clearfix')[0].find_all('dd')[1]
<dd>朝南</dd>
soup.find_all('div',class_='Z_home_b clearfix')[0].find_all('dd')[2]
<dd>3室1厅</dd>
soup.find_all('span',class_='ad')[0].text
'小区距3号线双墩站步行约542米'
re = requests.get('https://movie.douban.com/chart')
re.status_code
418
soup = BeautifulSoup(re.text,'lxml')

5.实践项目2:36kr信息抓取与邮件发送

本节内容为作者原创的项目,课程难度为5星,建议读者跟着课程一步一步的来,如果有不明白的地方,可以在群里面与其他伙伴进行交流。

在输出本节内容时,请注明来源,Datawhale自动化办公课程,谢谢~

如果没有多个邮箱,可以百度搜索临时邮箱进行实践学习
项目难度:⭐⭐⭐⭐⭐

完成了上面的实践项目1后,你膨胀到不行,觉得自己太厉害了。通过前面的学习,你了解到使用python进行电子邮件的收发,突然有一天你想到,如果我用A账户进行发送,同时用B账户进行接受,在手机上安装一个邮件接受的软件,这样就能完成信息从pc端投送到移动端。

在这样的思想上,就可以对动态变化的信息进行监控,一旦信息触发了发送的条件,可以将信息通过邮件投送到手机上,从而让自己最快感知到。

具体路径是:

python爬虫–>通过邮件A发送–>服务器—>通过邮件B接收

因此我们本节的内容就是爬取36kr的信息然后通过邮件发送

36kr官网:https://36kr.com/newsflashes

通过python发送邮件需要获得pop3的授权码

具体获取方式可参考:

https://blog.csdn.net/wateryouyo/article/details/51766345

接下来就爬取36Kr的网站

通过观察我们发现 消息的标签为
中国平安:推动新方正集团聚集医疗健康等核心业务发展
因此我们爬取的代码为

需要注意的是,邮箱发送消息用的HTML的模式,而HTML模式下换行符号为 < br>

def main(): print('正在爬取数据')url = 'https://36kr.com/newsflashes'headers = {'User-Agent': random.choice(user_agent)}response = requests.get(url, headers=headers)response=response.content.decode('utf-8', 'ignore')soup = BeautifulSoup(response, 'lxml')news = soup.find_all('a', class_='item-title')  news_list=[]for i in news:title=i.get_text()href='https://36kr.com'+i['href']news_list.append(title+'<br>'+href)info='<br></br>'.join(news_list)

接下来就是配置邮箱的发送信息

smtpserver = 'smtp.qq.com'# 发送邮箱用户名密码
user = ''
password = ''# 发送和接收邮箱
sender = ''
receive = ''def send_email(content):# 通过QQ邮箱发送title='36kr快讯'subject = titlemsg = MIMEText(content, 'html', 'utf-8')msg['Subject'] = Header(subject, 'utf-8')msg['From'] = sendermsg['To'] = receive# SSL协议端口号要使用465smtp = smtplib.SMTP_SSL(smtpserver, 465)  # 这里是服务器端口!# HELO 向服务器标识用户身份smtp.helo(smtpserver)# 服务器返回结果确认smtp.ehlo(smtpserver)# 登录邮箱服务器用户名和密码smtp.login(user, password)smtp.sendmail(sender, receive, msg.as_string())smtp.quit()
import requests
import random
from bs4 import BeautifulSoup
import smtplib  # 发送邮件模块
from email.mime.text import MIMEText  # 定义邮件内容
from email.header import Header  # 定义邮件标题smtpserver = 'smtp.qq.com'# 发送邮箱用户名密码
user = ''
password = ''# 发送和接收邮箱
sender = ''
receive = ''user_agent = ["Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50","Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50","Mozilla/5.0 (Windows NT 10.0; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0","Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; .NET4.0C; .NET4.0E; .NET CLR 2.0.50727; .NET CLR 3.0.30729; .NET CLR 3.5.30729; InfoPath.3; rv:11.0) like Gecko","Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)","Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0)","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)","Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:2.0.1) Gecko/20100101 Firefox/4.0.1","Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1","Opera/9.80 (Macintosh; Intel Mac OS X 10.6.8; U; en) Presto/2.8.131 Version/11.11","Opera/9.80 (Windows NT 6.1; U; en) Presto/2.8.131 Version/11.11","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_0) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Maxthon 2.0)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; TencentTraveler 4.0)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; The World)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Trident/4.0; SE 2.X MetaSr 1.0; SE 2.X MetaSr 1.0; .NET CLR 2.0.50727; SE 2.X MetaSr 1.0)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; 360SE)","Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; Avant Browser)"]def main():print('正在爬取数据')url = 'https://36kr.com/newsflashes'headers = {'User-Agent': random.choice(user_agent)}response = requests.get(url, headers=headers)response=response.content.decode('utf-8', 'ignore')soup = BeautifulSoup(response, 'lxml')news = soup.find_all('a', class_='item-title')  news_list=[]for i in news:title=i.get_text()href='https://36kr.com'+i['href']news_list.append(title+'<br>'+href)info='<br></br>'.join(news_list)print('正在发送信息')send_email(info)def send_email(content):# 通过QQ邮箱发送title='36kr快讯'subject = titlemsg = MIMEText(content, 'html', 'utf-8')msg['Subject'] = Header(subject, 'utf-8')msg['From'] = sendermsg['To'] = receive# SSL协议端口号要使用465smtp = smtplib.SMTP_SSL(smtpserver, 465)  # 这里是服务器端口!# HELO 向服务器标识用户身份smtp.helo(smtpserver)# 服务器返回结果确认smtp.ehlo(smtpserver)# 登录邮箱服务器用户名和密码smtp.login(user, password)smtp.sendmail(sender, receive, msg.as_string())smtp.quit()if __name__ == '__main__':main()
正在爬取数据
正在发送信息---------------------------------------------------------------------------TypeError                                 Traceback (most recent call last)<ipython-input-203-9e205b049b97> in <module>75 76 if __name__ == '__main__':
---> 77     main()<ipython-input-203-9e205b049b97> in main()53     info='<br></br>'.join(news_list)54     print('正在发送信息')
---> 55     send_email(info)56 57 def send_email(content):<ipython-input-203-9e205b049b97> in send_email(content)70     smtp.ehlo(smtpserver)71     # 登录邮箱服务器用户名和密码
---> 72     smtp.login(user, password)73     smtp.sendmail(sender, receive, msg.as_string())74     smtp.quit()C:\ProgramData\Anaconda3\lib\smtplib.py in login(self, user, password, initial_response_ok)719                 (code, resp) = self.auth(720                     authmethod, getattr(self, method_name),
--> 721                     initial_response_ok=initial_response_ok)722                 # 235 == 'Authentication successful'723                 # 503 == 'Error: already authenticated'C:\ProgramData\Anaconda3\lib\smtplib.py in auth(self, mechanism, authobject, initial_response_ok)629         if initial_response is not None:630             response = encode_base64(initial_response.encode('ascii'), eol='')
--> 631             (code, resp) = self.docmd("AUTH", mechanism + " " + response)632         else:633             (code, resp) = self.docmd("AUTH", mechanism)TypeError: can only concatenate str (not "bytes") to str

关于Datawhale: Datawhale是一个专注于数据科学与AI领域的开源组织,汇集了众多领域院校和知名企业的优秀学习者,聚合了一群有开源精神和探索精神的团队成员。Datawhale 以“for the learner,和学习者一起成长”为愿景,鼓励真实地展现自我、开放包容、互信互助、敢于试错和勇于担当。同时 Datawhale 用开源的理念去探索开源内容、开源学习和开源方案,赋能人才培养,助力人才成长,建立起人与人,人与知识,人与企业和人与未来的联结。 本次数据挖掘路径学习,专题知识将在天池分享,详情可关注Datawhale:


Task 05 Python 爬虫入门相关推荐

  1. Python爬虫入门教程:博客园首页推荐博客排行的秘密

    1. 前言 虽然博客园注册已经有五年多了,但是最近才正式开始在这里写博客.(进了博客园才知道这里面个个都是人才,说话又好听,超喜欢这里...)但是由于写的内容都是软件测试相关,热度一直不是很高.看到首 ...

  2. python爬虫入门教程(非常详细),超级简单的Python爬虫教程

    一.基础入门 1.1什么是爬虫 爬虫(spider,又网络爬虫),是指向网站/网络发起请求,获取资源后分析并提取有用数据的程序. 从技术层面来说就是 通过程序模拟浏览器请求站点的行为,把站点返回的HT ...

  3. python爬虫入门教程--优雅的HTTP库requests(二)

    requests 实现了 HTTP 协议中绝大部分功能,它提供的功能包括 Keep-Alive.连接池.Cookie持久化.内容自动解压.HTTP代理.SSL认证等很多特性,下面这篇文章主要给大家介绍 ...

  4. python爬虫入门教程--快速理解HTTP协议(一)

    http协议是互联网里面最重要,最基础的协议之一,我们的爬虫需要经常和http协议打交道.下面这篇文章主要给大家介绍了关于python爬虫入门之快速理解HTTP协议的相关资料,文中介绍的非常详细,需要 ...

  5. python爬虫入门代码-Python爬虫入门

    原标题:python爬虫入门 基础知识 HTTP协议 我们浏览网页的浏览器和手机应用客户端与服务器通信几乎都是基于HTTP协议,而爬虫可以看作是一个另类的客户端,它把自己伪装成浏览器或者手机应用客户端 ...

  6. python网络爬虫的基本步骤-黑客基础 编写Python爬虫入门步骤

    原标题:黑客基础 编写Python爬虫入门步骤 信息时代,数据就是宝藏.数据的背后隐含着无穷的宝藏,这些宝藏也许就是信息量所带来的商业价值,而大数据本身也将成为桌面上的筹码. 黑客花无涯 带你走进黑客 ...

  7. python爬虫程序实例-10个python爬虫入门实例

    作者:h3zh1 来源:cnblogs.com/h3zh1/p/12548946.html 今天为大家准备了几个简单的python爬虫入门实例,分享给大家. 涉及主要知识点:web是如何交互的 req ...

  8. python爬虫入门实例-终于领会python爬虫入门示例

    随着人工智能 大数据的火热 Python成为了广大科学家和普通大众的学习语言.在学习Python的过程中 有很多人感到迷茫 不知道自己该从什么地方入手,今天我们就来说一些新手该如何学习Python编程 ...

  9. python爬虫入门代码-Python爬虫入门(一) 网络爬虫之规则

    Python爬虫入门(一) 总述 本来早就想学习下python爬虫了,总是找各种借口,一直拖到现在才开始系统的学习. 我用的教程是中国大学MOOC上的由北京理工大学开设的Python网络爬虫与信息提取 ...

最新文章

  1. powershell创建iis站点、应用程序及应用程序池
  2. istringstream字符串流,实现类似字符串截取的功能,字符串流中的put,str()将流转换成为字符串string
  3. java8 默认方法_如何不使用Java 8默认方法
  4. 其他数据类型存储空间大小(信息学奥赛一本通-T1018)
  5. Golang实践录:静态资源文件整合:初步使用
  6. Flink入门训练--以New York City Taxi为例
  7. Excel弱爆了!这个工具30分钟完成了我一天的工作量!
  8. openstack中彻底删除计算节点的操作记录
  9. 远程培训教程之POWERPOINT2003
  10. 树莓派:openCV之火焰检测
  11. 10分钟JAVA从入门到放弃
  12. ORA-00932: 数据类型不一致: 应为 NUMBER, 但却获得NUMBER
  13. 阿里云服务器租用报价新鲜出炉(轻量和ECS价格)
  14. 英语六级考前急救100词 10个List
  15. TensorFlow 2019
  16. Zalando Postgres Operator 快速上手
  17. oracle使用sql关闭trace日志,Linux清理Oracle日志巧用close_trace命令释放误删trace文件...
  18. 旅游业如何使用数据分析?
  19. php微信自动回复开发,PHP微信开发之文本自动回复
  20. C语言实现输出1900—2000年中是闰年的年份

热门文章

  1. matlab 振动模拟,【使用MATLAB进行振动模拟】第一章【MATLAB基础】
  2. (iphone)x线性马达驱动电路
  3. 小米品牌:图腾化的胜利
  4. 总结提高关键词排名最全的41个技巧
  5. 计算机毕业设计_基于JavaWeb servlet的教师信息管理系统(源码+mysql+文档)
  6. Caché 从入门到精通
  7. 精通Java数组的艺术:从初学者到高手的进阶之路(一)
  8. 长难句——考研英语刘晓燕#2
  9. CleanMyMac X4.11经典免费版本功能介绍
  10. GLaDOS加速网络套餐edu教育网邮箱免费使用