用Python爬取百度搜索结果
一、前言
众所周知,百度上直接搜索关键字会出来一大堆东西,时常还会伴随有广告出现,不小心就点进去了,还得花时间退出来,有些费劲。
最近群里有个小伙伴提出一个需求,需要获取百度上关于粮食的相关讲话文章标题和链接。正好小编最近在学习爬虫,就想着拿这个需求来练练手。我们都知道,对Python来说,有大量可用的库,实现起来并不难,动手吧。
二、项目目标
爬取百度上关键字为“粮食”的搜索结果,并保存,提交给客户,用于进一步分析我国粮食政策。
三、项目准备
软件:PyCharm
需要的库:json,requests,etree
四、项目分析
1)如何进行关键词搜索?
利用response库,直接Get网址获得搜索结果。
2)如何获取标题和链接?
利用etree对原代码进行规范梳理后,通过Xpath定位到文章标题和href,获取标题和文章链接。
3)如何保存搜索结果?
新建txt文件,对搜索结果循环写入,保存即可。
五、项目实现
1、第一步导入需要的库
importjson
importrequests
fromlxmlimportetree
2、第二步用requests进行请求搜索
headers={
"User-Agent":"Mozilla/5.0(WindowsNT10.0;WOW64)AppleWebKit/537.36(KHTML,likeGecko)Chrome/88.0.4324.104Safari/537.36"
}
response=requests.get('https://www.baidu.com/s?wd=粮食&lm=1',headers=headers)
3、第三步对获取的源代码进行整理分析,通过Xpath定位需要的资源
r=response.text
html=etree.HTML(r,etree.HTMLParser())
r1=html.xpath('//h3')
r2=html.xpath('//*[@class="c-abstract"]')
r3=html.xpath('//*[@class="t"]/a/@href')
4、第四步把有用资源循环读取保存
foriinrange(10):
r11=r1[i].xpath('string(.)')
r22=r2[i].xpath('string(.)')
r33=r3[i]
withopen('ok.txt','a',encoding='utf-8')asc:
c.write(json.dumps(r11,ensure_ascii=False)+'\n')
c.write(json.dumps(r22,ensure_ascii=False)+'\n')
c.write(json.dumps(r33,ensure_ascii=False)+'\n')
print(r11,end='\n')
print('------------------------')
print(r22,end='\n')
print(r33)
以上内容为大家介绍了用Python爬取百度搜索结果,希望对大家有所帮助,如果想要了解更多Python相关知识,请关注IT培训机构:千锋教育。http://www.mobiletrain.org/

猜你喜欢LIKE
相关推荐HOT
更多>>
python中的filter函数功能是什么?
python中的filter函数功能是什么?在python中,面对众多的数据,我们要过滤筛选出我们需要的数据。python中的filter函数就是起到了过滤筛选的作...详情>>
2023-11-10 20:37:27
pythontime模块是什么
pythontime模块是什么在python中使用时间,就免不了和time模块打交道,另外两个模块这个暂时先不做介绍。做time模块的使用上,我们可以用它来对...详情>>
2023-11-10 15:53:16
python是什么编程语言
python是什么编程语言1、说明是一种面向对象、解释型计算机程序设计语言,由GuidovanRossum于1989年底发明,第一个公开发行版发行于1991年。Pyt...详情>>
2023-11-10 15:21:05
python异常处理的两种技巧
python异常处理的两种技巧1、传递异常有时我们会在捕捉到一个异常后重新引发它(传递异常),实现起来很简单,使用不带参数的raise语句即可。deff...详情>>
2023-11-10 14:49:39热门推荐
python中的filter函数功能是什么?
沸python delattr函数如何使用?
热python中pdb模块怎么用?
热Python如何截图保存?
新python中缺少module怎么办?
python strftime和strptime的不同分析
python time.strptime的格式化
python中@contextmanager是什么?
python对象的三要素是什么
pythonGIL在Python多线程的应用
python如何对多个CSV文件进行读取
pythonif嵌套命令如何理解?
python对列表进行永久性或临时排序的方法
python生成器调用方法引发异常
技术干货






