首先介紹一下我們用360搜索派取城市排名前20。
我们爬取的网址:https://baike.so.com/doc/24368318-25185095.html
我们要爬取的内容:
html字段:
robots协议:
现在我们开始用python IDLE 爬取
import requests r = requests.get("https://baike.so.com/doc/24368318-25185095.html") r.status_code r.text
结果分析,我们可以成功访问到该网页,但是得不到网页的结果。被360搜索识别,我们将headers修改。
输出有个小插曲,网页内容很多,我是想将前500个字符输出,第一次格式错了
import requests headers = { 'Cookie':'OCSSID=4df0bjva6j7ejussu8al3eqo03', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' '(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36', } r = requests.get("https://baike.so.com/doc/24368318-25185095.html", headers = headers) r.status_code r.text
接着我们对需要的内容进行爬取,用(.find)方法找到我们内容位置,用(.children)下行遍历的方法对内容进行爬取,用(isinstance)方法对内容进行筛选:
import requests from bs4 import BeautifulSoup import bs4 headers = { 'Cookie':'OCSSID=4df0bjva6j7ejussu8al3eqo03', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' '(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36', } r = requests.get("https://baike.so.com/doc/24368318-25185095.html", headers = headers) r.status_code r.encoding = r.apparent_encoding soup = BeautifulSoup(r.text, "html.parser") for tr in soup.find('tbody').children: if isinstance(tr, bs4.element.Tag): tds = tr('td') print([tds[0].string, tds[1].string, tds[2].string])
得到结果如下:
修改输出的数目,我们用Clist列表来存取所有城市的排名,将前20个输出代码如下:
import requests from bs4 import BeautifulSoup import bs4 Clist = list() #存所有城市的列表 headers = { 'Cookie':'OCSSID=4df0bjva6j7ejussu8al3eqo03', 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36' '(KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36', } r = requests.get("https://baike.so.com/doc/24368318-25185095.html", headers = headers) r.encoding = r.apparent_encoding #将html的编码解码为utf-8格式 soup = BeautifulSoup(r.text, "html.parser") #重新排版 for tr in soup.find('tbody').children: #将tbody标签的子列全部读取 if isinstance(tr, bs4.element.Tag): #筛选tb列表,将有内容的筛选出啦 tds = tr('td') Clist.append([tds[0].string, tds[1].string, tds[2].string]) for i in range(21): print(Clist[i])
最终结果:
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“Python用requests库爬取返回为空的解决办法”评论...
更新日志
2024年07月03日
2024年07月03日
- 魔兽世界奥格瑞玛怎么去幽暗城 奥格瑞玛去幽暗城方法介绍
- 《间谍过家家日记大作战》成就攻略一览
- 完美的音乐品质-群星《红酒杯发烧酒廊情歌》2CD[WAV]
- 群星.2011《高雄国际Hi-End音响大展纪念发烧金碟》[WAV分轨]
- 康康1999-催泪[阿尔法][WAV+CUE]
- 和守望先锋太像?《星鸣特攻》开发商:我们与众不同
- 速通玩家有福了!夏季游戏速通大会正在火热进行中
- 《使命召唤》新处决动作曝光 或联动《死侍3》?
- 《陈百强出道35周年 文质翩翩》4CD[WAV+CUE][1.8GB]
- 邓丽君《思君集》3CD[WAV+CUE][1.2GB]
- 华语流行S.H.E《12CD》2001~2010[APE+CUE][3.7GB]
- 北风之望饮品怎么调配?饮品调酒配方分享
- 原画壁纸及美图第254期,无水印可自取
- 原画壁纸及美图第255期,无水印可自取
- 群星.1991-宝丽金冬日浓情【宝丽金】【WAV+CUE】