Python爬虫实例(含代码)超详细教程

876次阅读
没有评论

文章目录


前言

这篇文章会列举几个学python爬虫的简单例子。


一、搜狗爬取周杰伦

进入搜狗首页,在搜索引擎中输入周杰伦,进入周杰伦首页。Python爬虫实例(含代码)超详细教程
我们得到了网址"https://www.sogou.com/web?query=周杰伦",即拿到了url=“https://www.sogou.com/web?query=周杰伦”。
右键 ->检查,进入下图界面
Python爬虫实例(含代码)超详细教程
刷新一下,点击网络(network),选择标头,可以看到请求URL、请求方式、状态码等等信息,往下拉看到User-Agent,做为headers,避免反爬。

import requests url="https://www.sogou.com/web?query=周杰伦" headers={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55" } #以字典的形式设置请求头,处理反爬 resp=requests.get(url,headers=headers) print(resp) #结果:<Response [200]> print(resp.text) #拿到页面源代码 resp.close() #关掉resp

上述案例可以进一步改进,实现查询自由,代码如下:

import requests query=input("请输入一个你喜欢的明星:") url=f"https://www.sogou.com/web?query={query}" headers={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55" } resp=requests.get(url,headers=headers) print(resp) print(resp.text) #拿到页面源代码 resp.close() #关闭resp

二、百度翻译

代码如下

import requests url="https://fanyi.baidu.com/sug" s=input("请输入要翻译的英文单词") dat={ "kw":s } resp=requests.post(url,data=dat)#发送post请求,发送的数据必须放在字典中,通过data参数进行传递 print(resp.json()) #将服务器返回的内容直接处理成json => dict resp.close()

Python爬虫实例(含代码)超详细教程

三、豆瓣电影

代码如下:

import requests url="http://movie.douban.com/j/chart/top_list" param={ "type":"24", "interval_id":"100:90", "action":"", "start":0, "limit":20, } #右键->检查,network,点击Payload即可将参数复制到此处的字典 headers={ "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.71 Safari/537.36 Edg/97.0.1072.55" } resp=requests.get(url=url,params=param,headers=headers) print(resp.json()) resp.close() #关掉resp

Python爬虫实例(含代码)超详细教程


总结

这里对文章进行总结:以上就是今天要讲的内容,本文介绍了简单的爬虫案例,希望对大家有所帮助哟!

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:Python教程2022-10-24发表,共计1629字。
新手QQ群:570568346,欢迎进群讨论 Python51学习