Python电商爬虫保姆级入门教程(纯新手向)

图片

图灵Python课堂

长沙图灵教育于2001年开始进入教育行业,立足泛IT类职业教育,以打造高新技术人才为宗旨,专注于提供多层次、个性化的职业技能培训课程,为各行业培养技术开发、应用和管理等岗位的中高端人才,致力于成为优质的职业教育内容提供商。

01

Python优势

对于网络爬虫开发来说,Python有着无与伦比天然优势,这里从两个方面对其优势进行分析与讲解。

1、抓取网页本身的电商商品详情API接口

相比其他静态编程语言(如java、c#与c++)Python抓取网页文档的接口更简洁,而对比其他动态脚本语言(如perl,shell)Python的urllib包提供了较为完整的访问网页文档的API。

此外,抓取网页有时候需要模拟浏览器的行为,很多网站对于生硬的爬虫抓取都是封杀的。此时,需要模拟user agent的行为来构造合适的请求(模拟用户登录、模拟session/cookie的存储和设置)。在Python里都有非常优秀的第三方包帮助搞定这些工作(如Requests,mechanize)。

2、网页抓取后的处理

抓取的网页通常需要处理,比如过滤html标签,提取文本等。Python的beautifulsoap提供了简洁的文档处理功能,能用极短的代码完成大部分文档的处理。

其实以上功能很多语言和工具都能做,但是用Python能够干得最快,最干净。

Life is short, you need python.

PS:python2.x和python3.x有很大不同,本文只讨论python3.x的爬虫实现方法。

02

爬虫框架

URL管理器:管理待爬取的url集合和已爬取的url集合,传送待爬取的url给网页下载器。

网页下载器(urllib):爬取url对应的网页,存储成字符串,传送给网页解析器。

网页解析器(BeautifulSoup):解析出有价值的数据,存储下来,同时补充url到URL管理器。

03

URL管理器

基本功能

  • 添加新的url到待爬取url集合中。

  • 判断待添加的url是否在容器中(包括待爬取url集合和已爬取url集合)。

  • 获取待爬取的url。

  • 判断是否有待爬取的url。

  • 将爬取完成的url从待爬取url集合移动到已爬取url集合。

存储方式

1、内存(python内存)
待爬取url集合:set()
已爬取url集合:set()

2、关系数据库(mysql)
urls(url, is_crawled)

3、缓存(redis)
待爬取url集合:set
已爬取url集合:set

大型互联网公司,由于缓存数据库的性能高,所以一般把url存储在缓存数据库中。小型公司,一般把url存储在内存中,要永久存储,则存储到关系数据库中。

05

网页下载器urllib

将url对应的网页下载到本地,存储成一个文件或字符串。

基本方法

新建baidu.py,内容如下:

import urllib.request
response = urllib.request.urlopen('http://www.baidu.com')buff = response.read()html = buff.decode("utf8")print(html)
 
 

命令行中执行python baidu.py,则可以打印出获取到的页面。

构造Request

上面的代码,可以修改为:

import urllib.requestrequest = urllib.request.Request('http://www.baidu.com')response = urllib.request.urlopen(request)buff = response.read()html = buff.decode("utf8")print(html)
 
 

携带参数

新建baidu2.py,内容如下:

import urllib.requestimport urllib.parse
url = 'http://www.baidu.com'values = {'name': 'voidking','language': 'Python'}data = urllib.parse.urlencode(values).encode(encoding='utf-8',errors='ignore')headers = { 'User-Agent' : 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0' }request = urllib.request.Request(url=url, data=data,headers=headers,method='GET')response = urllib.request.urlopen(request)buff = response.read()html = buff.decode("utf8")print(html)
 
 

使用Fiddler监听数据

要查看请求是否真的携带了参数,需使用fiddler。

添加处理器

 
 

import urllib.requestimport http.cookiejar# 创建cookie容器cj = http.cookiejar.CookieJar()# 创建openeropener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))# 给urllib.request安装openerurllib.request.install_opener(opener)# 请求request = urllib.request.Request('http://www.baidu.com/')response = urllib.request.urlopen(request)buff = response.read()html = buff.decode("utf8")print(html)print(cj)

06

网页解析器(BeautifulSoup)

从网页中提取出有价值的数据和新的url列表。

解析器选择

为了实现解析器,可以选择使用正则表达式、html.parser、BeautifulSoup、lxml等,这里选择BeautifulSoup。其中,正则表达式基于模糊匹配,而另外三种则是基于DOM结构化解析。

BeautifulSoup安装测试

1、安装,在命令行下执行pip install beautifulsoup4。
2、测试

 
 

import bs4print(bs4)

基本用法

1、创建BeautifulSoup对象

 
 

import bs4from bs4 import BeautifulSoup

# 根据html网页字符串创建BeautifulSoup对象html_doc = """<html><head><title>The Dormouse's story</title></head><body><p class="title"><b>The Dormouse's story</b></p><p class="story">Once upon a time there were three little sisters; and their names were<a href="http://example.com/elsie" class="sister" id="link1">Elsie</a>,<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and<a href="http://example.com/tillie" class="sister" id="link3">Tillie</a>;and they lived at the bottom of a well.</p><p class="story">...</p>"""soup = BeautifulSoup(html_doc)print(soup.prettify())

2、访问节点

 
 

print(soup.title)print(soup.title.name)print(soup.title.string)print(soup.title.parent.name)

print(soup.p)print(soup.p['class'])

3、指定tag、class或id

 
 

print(soup.find_all('a'))print(soup.find('a'))print(soup.find(class_='title'))print(soup.find(id="link3"))print(soup.find('p',class_='title'))

4、从文档中找到所有<a>标签的链接

 
 

for link in soup.find_all('a'):    print(link.get('href'))

出现了警告,根据提示,在创建BeautifulSoup对象时,指定解析器即可。

 
 

soup = BeautifulSoup(html_doc,'html.parser')

5、从文档中获取所有文字内容

 
 

print(soup.get_text())

6、正则匹配

 
 

link_node = soup.find('a',href=re.compile(r"til"))print(link_node)

猜你喜欢

转载自blog.csdn.net/onebound_linda/article/details/131892097