Python爬虫:如何爬虫实现以及2大解析方法

时间:2024-10-17 22:02:46

1、基础爬虫的固定模式我们这里说的基础爬虫,是指无需处理验证码、代理、异象异步加载等高阶爬虫技术的爬虫形式。通常来说,基础爬虫的两大请求库 urllib 和 requests 中 requests 一般是被绝大部分人所喜欢的,即使Urllib的功能也算齐全。两大解析库 BeautifulSoup 由于本身强大的Html文档解析能力而深受喜爱,另外一种解析库 lxml 在搭配 xpath 表达式的基础上也大大提升了效率。就基础爬虫来讲,两大请求库和两大解析库的组合方式能根据个人喜好去选择。

Python爬虫:如何爬虫实现以及2大解析方法

2、比较常用的爬虫组合工具是:requests + BeautifulSouprequests + lxml同一网页爬虫的四种实现方式假如要抓取每条新闻的标题和链接,并把其组合为一个字典的结构打印出来。第一步查看Html源码明确新闻标题信息组织结构。能够目标信息存在于 em 标签下 a 标签内的文本和 href 属性中。可随时借助 requests 库构造请求,并用 BeautifulSoup 或者 lxml 进行解析。

Python爬虫:如何爬虫实现以及2大解析方法

3、方式一: requests + BeautifulSoup + select css选择器# select methodimport requestsfrom bs4 import BeautifulSoupheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36'}url = 'http://news.qq.com/'Soup = BeautifulSoup(requests.get(url=url, headers=headers).text.encode("utf-8"), 'lxml')em = Soup.select('em[class="f14 l24"] a')for i in em:title = i.get_text()link = i['href'] print({'标题': title,'链接': link})select methodimport requestsfrom bs4 import BeautifulSoupheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36'}url = 'http://news.qq.com/'Soup = BeautifulSoup(requests.get(url=url, headers=headers).text.encode("utf-8"), 'lxml')em = Soup.select('em[class="f14 l24"] a')for i in em:title = i.get_text()link = i['href'] print({'标题': title,'链接': link})

Python爬虫:如何爬虫实现以及2大解析方法

4、方式二:requests+BeautifulSoup+find_all进行信息提取# find_all methodimport requestsfrom bs4 import BeautifulSoupheaders = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.119 Safari/537.36'}url = 'http://news.qq.com/'Soup = BeautifulSoup(requests.get(url=url, headers=headers).text.encode("utf-8"), 'lxml')em = Soup.find_all('em', attrs={'class': 'f14 l24'})for i in em:title = i.a.get_text()link = i.a['href']print({'标题': title,'链接': link})同样是 requests + BeautifulSoup 的爬虫组合,但在信息提取上采用了 find_all 的方式。九州IP能让你随时切换需要的IP地址。

© 手抄报圈