鱼C论坛

 找回密码
 立即注册
查看: 839|回复: 3

爬虫正则表达式问题

[复制链接]
发表于 2019-3-10 18:33:00 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
爬取淘宝页面商品信息
正则表达式好像不对,没有爬到信息
  1. import requests
  2. import re

  3. def getHtmlText(url):
  4.     try :
  5.         r = request.get(url,timeout = 30)
  6.         r.raise_for_status()
  7.         r.encoding = r.apparent_encoding
  8.         return r.text
  9.     except:
  10.         return ""

  11. def parserPage(ilt,html):
  12.     try:
  13.         plt = re.findall(r'"view_price":\d"',html)
  14.         tlt = re.findall(r'"raw_title":".*?"',html)
  15.         for i in range(len(plt)):
  16.             price = eval(pat[i].split(':')[1])
  17.             title = eval(tlt[i].split(':')[1])
  18.             ilt.append([price,title])
  19.     except:
  20.         return 0

  21. def printGoodList(lit):
  22.     tplt = "{:4}\t{:8}\t{:16}"
  23.     print(tplt.format("序号","价格","商品名称"))
  24.     count = 0
  25.     for g in lit:
  26.         count = count + 1
  27.         print(tplt.format(count,g[0],g[1]))


  28. def main():
  29.     goods = '书包'
  30.     depth = 2
  31.     start_url = "https://s.taobao.com/search?q=" + goods
  32.     infoList = []
  33.     for i in range (depth):
  34.         try :
  35.             url = start_url + '&s='+ str(44*i)
  36.             html = getHtmlText(url)
  37.             parsePage(infoList,html)
  38.         except:
  39.             continue

  40.     printGoodList(infoList)
  41.    
  42.         
  43. main()
复制代码


求大佬指正
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2019-3-10 22:52:32 | 显示全部楼层
本帖最后由 yjsx86 于 2019-3-10 22:59 编辑

先不说正则的问题
你用代码去访问https://s.taobao.com/search?q=书包 , 会被302重定向到登录界面 可以开个隐身窗口去测试
你需要先解决登录淘宝的问题
爬虫不是说爬就爬的,登录淘宝后再看看请求https://s.taobao.com/search?q=书包,时需要带些什么cookie
带cookie访问网页 获取html代码,看看是否有你需要的数据,没有的话数据就可能在json里或者是由js拼接的
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-3-11 09:50:18 | 显示全部楼层
你确定你获取到内容了??

淘宝现在除了需要登陆的曲奇,还要一堆人类操作的触发的js生成的曲奇才能获取到正确的内容。

小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-3-11 16:51:45 | 显示全部楼层
爬虫用正则好麻烦,建议用CSS或者XPATH
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2026-1-14 12:14

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表