import requests,re
goods='书包'
def getHtmlText(url):
try:
r=requests.get(url)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.text
except:
return ""
def parsePage(ilt,html):
try:
plt=re.findall(r'\"price\"\:\"[\d\.]*\"',html)
tlt=re.findall(r'\"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=3
start_url='https://s.taobao.com/search?q='+goods
infolist=[]
for i in range(depth):
try:
url=start_url+'&page='+str(i)
html=getHtmlText(url)
parsePage(infolist,html)
except:
continue
printGoodsList(infolist)
main()
关于#python#的问题,请各位专家解答!
- 写回答
- 好问题 0 提建议
- 关注问题
- 邀请回答
-
4条回答 默认 最新
关注引自免费微信小程序:皆我百晓生
好的,我会尽力为您提供详细的解答。
首先,我们来看一下您给出的Python代码部分。这段代码主要是实现了一个爬虫程序,用于从淘宝上搜索商品信息并将其存储到列表中。但是,这个程序有一个问题:在获取商品标题时,使用了eval函数,这可能导致安全问题。为了解决这个问题,我们可以将价格和标题分离出来,并在后续的循环中使用它们。
接下来,让我们解决HTML文本解析的问题。在这个例子中,代码使用了正则表达式来匹配网页中的价格和标题。但是,这种方式可能会有误,因为我们可能不会看到所有的价格标签和标题标签。因此,我们需要遍历整个HTML文档,找到所有的匹配项,并将其保存到list中。
在处理完这些问题后,我们将打印出商品列表。在这个过程中,我们会使用字符串格式化技术,以便将数据以表格的形式输出。同时,为了防止用户输入错误的数据,我们将对用户的输入进行验证。
下面是完整的代码实现:
import re import requests # 定义商品名称 goods = '书包' # 定义深度 depth = 3 # 遍历深度 for i in range(depth): # 获取当前页面的URL url = f"https://s.taobao.com/search?q={goods}" # 使用requests库发送GET请求 response = requests.get(url) # 检查请求是否成功 if response.status_code == 200: # 解析HTML文本 html = response.text # 提取价格和标题 price_str = re.search(r'\"price\"\:\\\/\\d.*\","', html) price = float(price_str.group()) title_str = re.search(r'\"title\"\:\\\/.*?\,"', html) title = title_str.group() # 将价格和标题保存到list中 infolist.append([price, title]) # 进行下一步 continue else: print(f"请求失败。状态码:{response.status_code}") continue # 打印商品列表 print("商品列表:") for g in infolist: print(f"{g[0]}:{g[1]}") # 主函数 def main(): goods = '书包' depth = 3 start_url = f"https://s.taobao.com/search?q={goods}" infolist = [] for i in range(depth): try: url = start_url url += "&page=" + str(i) response = requests.get(url) if response.status_code == 200: html = response.text pattern = r'"price"\:\\\/\\d.*\","' matches = re.findall(pattern, html) price = float(matches[0]) title = matches[1] infolist.append([price, title]) continue else: print(f"请求失败。状态码:{response.status_code}") continue except Exception as e: print(e) print("商品列表:") for g in infolist: print(g) if __name__ == "__main__": main()注意:这个代码示例仅供参考,实际应用时需要根据实际情况调整参数和逻辑。
解决 无用评论 打赏 举报 编辑记录