0
点赞
收藏
分享

微信扫一扫

Python网络爬虫之爬取淘宝网页页面 MOOC可以运行的代码


可以实现功能的全部代码:

import requests
import re


def getHTMLText(url):
try:
r = requests.get(url, timeout = 30)
r.raise_for_status()
r.encoding = r.apparent_encoding
return r.text
except:
return ""

def parsePage(ilt, html):
try:
plt = re.findall(r'\"view_price\"\:\"[\d\.]*\"',html)
tlt = re.findall(r'\"raw_title\"\:\".*?\"',html)
for i in range(len(plt)):
price = eval(plt[i].split(':')[1])
title = eval(tlt[i].split(':')[1])
ilt.append([price,title])
except:
print("")

def printGoodsList(ilt):
tplt = "{:4}\t{:8}\t{:16}"
print(tplt.format("序号","价格","商品名称"))
count = 0
for g in ilt:
count = count + 1
print(tplt.format(count,g[0],g[1]))

def main():
goods = '书包'
depth = 2
start_url = 'https://s.taobao.com/search?q=' + goods
infoList = []
for i in range(depth):
try:
url = start_url + '&s=' + str(44*i)
html = getHTMLText(url)
parsePage(infoList, html)
except:
continue
printGoodsList(infoList)

main()

运行示例:

Python网络爬虫之爬取淘宝网页页面 MOOC可以运行的代码_html


无论爬取什么网页都要先看看robots协议。

淘宝的robots协议:

User-agent: *
Disallow: /

Python网络爬虫之爬取淘宝网页页面 MOOC可以运行的代码_html_02


但是,我们模仿人一样的频率去爬去就没事啦。

程序的结构设计:

步骤1:提交商品搜索请求,循环获取页面

步骤2:对于每个页面,提取商品名称和价格信息

步骤3:将信息输出到屏幕上

Python网络爬虫之爬取淘宝网页页面 MOOC可以运行的代码_查看源代码_03

查看源代码:价格在view_prince里面。

Python网络爬虫之爬取淘宝网页页面 MOOC可以运行的代码_搜索_04


Python网络爬虫之爬取淘宝网页页面 MOOC可以运行的代码_查看源代码_05

要注意对齐的方式,这样就没错误:

Python网络爬虫之爬取淘宝网页页面 MOOC可以运行的代码_查看源代码_06


但是这样就会报错:

Python网络爬虫之爬取淘宝网页页面 MOOC可以运行的代码_查看源代码_07


举报

相关推荐

0 条评论