Python3实现爬虫爬取赶集网列表功能【基于request和BeautifulSoup模块】

时间:2021-10-14 08:55:52

本文实例讲述了python3实现爬虫爬取赶集网列表功能。分享给大家供大家参考,具体如下:

python3爬虫之爬取赶集网列表。这几天一直在学习使用python3爬取数据,今天记录一下,代码很简单很容易上手。

首先需要安装python3。如果还没有安装,可参考本站前面关于python3安装与配置相关文章。

首先需要安装request和beautifulsoup两个模块

request是python的http网络请求模块,使用requests可以轻而易举的完成浏览器可有的任何操作

?
1
pip install requests

beautifulsoup是用python写的一个html/xml的解析器,它可以很好的处理不规范标记并生成剖析树

?
1
pip install beautifulsoup4

代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
from urllib import request
from bs4 import beautifulsoup
#构造头文件,模拟浏览器访问
url="http://xa.ganji.com/meirdjm/o2/"
headers = {'user-agent':'mozilla/5.0 (windows nt 6.1; win64; x64) applewebkit/537.36 (khtml, like gecko) chrome/70.0.3538.77 safari/537.36'}
page = request.request(url,headers=headers)
# 发送请求,获取内容
page_info = request.urlopen(page).read().decode('utf-8')
# 将获取到的内容转换成beautifulsoup格式,并将html.parser作为解析器
soup = beautifulsoup(page_info, 'html.parser')
# 查找所有a标签中class='list-info-title'
titles = soup.find_all('a',class_="list-info-title")
# 打印抓取到的title
for title in titles:
 print(title.string)

结果:

Python3实现爬虫爬取赶集网列表功能【基于request和BeautifulSoup模块】

希望本文所述对大家python程序设计有所帮助。

原文链接:https://blog.csdn.net/ziwoods/article/details/84250755