python3爬取淘宝信息代码分析

yipeiwu_com6年前Python爬虫
# encoding:utf-8
import re # 使用正则 匹配想要的数据
import requests # 使用requests得到网页源码

这个函数是用来得到源码

# 得到主函数传入的链接
def getHtmlText(url):
  try: # 异常处理
    # 得到你传入的URL链接 设置超时时间3秒
    r = requests.get(url, timeout=3)
    # 判断它的http状态码
    r.raise_for_status()
    # 设置它的编码 encoding是设置它的头部编码 apparent_encoding是从返回网页中分析它的编码格式
    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)
    # 找到书包的地址
    add = re.findall(r'\"item_loc\"\:\".*?\"', html)
    # 找到书包的图片链接
    img = re.findall(r'\"pic_url\"\:\".*?\"', html)
    # 得到这个内容放入主函数中的列表
    for i in range(len(plt)):
      price = eval(plt[i].split(':')[1])
      title = eval(tlt[i].split(':')[1])
      address = eval(add[i].split(':')[1])
      imgs = eval(img[i].split(':')[1])  
      ilt.append([price, title, address, imgs])
  except: # 放生异常输出空字符串
    print('')
# 得到主函数传入的列表
def printGoodsList(ilt):
  # 每个列之间用tplt的放是隔开
  tplt = '{:4}\t{:8}\t{:16}\t{:32}'
  # 这个是整个的标题
  print(tplt.format('序号', '价格', '商品名称','地址', '图片地址'))
  count = 0 # 统计有多少的序号
  for g in ilt:
    count = count + 1 # 循环一遍加一
    print(tplt.format(count, g[0], g[1], g[2]), g[3]) # 输出你得到的数据
# 定义主函数 main
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) # 得到url传入到你要得到url的函数中
      parsePage(infoList, html) # 得到你的html源码 放入解析的网页中
    except: # 发生异常跳过
      continue
  # 把列表中的数据放入解析的函数中
  printGoodsList(infoList)
# 代码调试片段
if __name__ == '__main__':
  main() # 调用主函数

以上就是经过小编测试过的用python3爬取淘宝信息的代码,大家测试后如果还有任何不明白的地方可以在下方的留言区讨论。

相关文章

Python爬虫模拟登录带验证码网站

Python爬虫模拟登录带验证码网站

爬取网站时经常会遇到需要登录的问题,这是就需要用到模拟登录的相关方法。python提供了强大的url库,想做到这个并不难。这里以登录学校教务系统为例,做一个简单的例子。 首先得明白coo...

Python爬虫之xlml解析库(全面了解)

1.Xpath Xpath是一门在XML中查找信息的语言,可用来在XML文档中对元素和属性进行遍历。XQuery和xpoint都是构建于xpath表达之上 2.节点 父(parent),...

Python爬虫工程师面试问题总结

注:答案一般在网上都能够找到。 1.对if __name__ == 'main'的理解陈述 2.python是如何进行内存管理的? 3.请写出一段Python代码实现删除一个lis...

python爬虫项目设置一个中断重连的程序的实现

做爬虫项目时,我们需要考虑一个爬虫在爬取时会遇到各种情况(网站验证,ip封禁),导致爬虫程序中断,这时我们已经爬取过一些数据,再次爬取时这些数据就可以忽略,所以我们需要在爬虫项目中设置一...

python爬取网页转换为PDF文件

python爬取网页转换为PDF文件

爬虫的起因 官方文档或手册虽然可以查阅,但是如果变成纸质版的岂不是更容易翻阅与记忆。如果简单的复制粘贴,不知道何时能够完成。于是便开始想着将Android的官方手册爬下来。 全篇的实...