说明
Scrapy爬虫案例-淘宝比价定向爬虫学习笔记
学习教程:Python网络爬虫与信息提取
授课老师:嵩天
官方网站:https://python123.io
教程链接:https://python123.io/index/courses/804
“淘宝比价定向爬虫”实例
功能描述
目标:获取淘宝搜索页面的信息,提取其中的商品名称和价格
理解:
- 淘宝的搜索接口
- 翻页的处理
- 技术路线:requests‐bs4‐re
关键词:“蕾丝裙”
https://s.taobao.com/search?q=%E8%95%BE%E4%B8%9D%E8%A3%99&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20170105&ie=utf8&bcoffset=0&ntoffset=6&p4ppushleft=1%2C48&s=1
https://s.taobao.com/search?q=%E8%95%BE%E4%B8%9D%E8%A3%99&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20170105&ie=utf8&bcoffset=0&ntoffset=6&p4ppushleft=1%2C48&s=44
https://s.taobao.com/search?q=%E8%95%BE%E4%B8%9D%E8%A3%99&js=1&stats_click=search_radio_all%3A1&initiative_id=staobaoz_20170105&ie=utf8&bcoffset=0&ntoffset=6&p4ppushleft=1%2C48&s=88
每页44个商品
搜索接口和翻页的URL对应属性
定向爬虫的可行性
https://s.taobao.com/robots.txt
User‐agent: *
Disallow: /
请注意:这个例子仅探讨技术实现,请不要不加限制的爬取该网站
程序的结构设计
步骤1:提交商品搜索请求,循环获取页面
步骤2:对于每个页面,提取商品名称和价格信息
步骤3:将信息保存到txt
实例编写
#!/usr/bin/env python
# coding=utf-8
"""
项目描述:获取淘宝搜索页面的信息,提取其中的商品名称和价格
运行环境:win7 64 + python3.7
三方库:fake_useragent
代码详解:https://yangyang188.coding.me/
文件: TaobaoSpider.py
创建时间:2019/8/11 9:21
创建者:yangyang
博客: yangyang188.coding.me
"""
import requests
import re
from fake_useragent import UserAgent
# 设置随机ua
ua = UserAgent()
headers = {
'User-Agent': ua.random,
'cookie': '***'
}
def getHTMLText(url):
try:
r = requests