# -*- coding: utf-8 -*-
import requests
import re
def getHTMLText(url):
try:
kv = {"User-Agent": 'Mozilla/5.0'}
r = requests.get(url, timeout=30,headers=kv)
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("1", "2", "3"))
count = 0
for g in ilt:
count = count + 1
print(tplt.format(count, g[0], g[1]))
def main():
goods = '书包'
depth = 3
start_url = ''
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的requests库从淘宝网站爬取特定商品信息,并将这些信息存储在一个列表中。它使用了正则表达式来从HTML中提取价格和商品标题。
以下是代码的详细解释:
getHTMLText(url)
: 这个函数用于获取指定URL的HTML文本。它使用了requests库来发送GET请求,并设置了一些请求头(特别是User-Agent)以模拟浏览器。如果请求成功,它会返回HTML文本;如果失败,返回一个空字符串。parsePage(ilt, html)
: 这个函数用于从HTML文本中提取价格和商品标题,并将它们存储在一个列表中。它使用正则表达式来查找特定的字符串模式,然后使用eval函数将匹配到的字符串解析为Python对象。printGoodsList(ilt)
: 这个函数用于打印提取到的商品信息。它首先打印一个表头,然后遍历存储商品信息的列表,并打印出每个商品的价格和标题。main()
: 这是程序的入口点。它首先定义了一些变量(商品名称和要搜索的深度),然后构造了初始的搜索URL。然后,它进行一定深度的搜索,每次搜索都会获取一页的商品信息,并使用parsePage
函数解析这些信息。最后,它调用printGoodsList
函数打印出所有找到的商品信息。