鱼C论坛

 找回密码
 立即注册
查看: 1103|回复: 9

[已解决]python爬虫多页爬取

[复制链接]
发表于 2022-1-24 13:58:16 | 显示全部楼层 |阅读模式

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

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

x
本帖最后由 2022@lif 于 2022-1-25 08:30 编辑

爬取网址https://list.szlcsc.com/catalog/439.html中的所有产品的信息,发现在此页面翻页时网址的url不会变。查看网络请求时发现这些页面页数信息应该是存放在Payload中的表单数据中:


                               
登录/注册后可看大图

但是我发起POST请求时携带了这些参数,并不能得到这个页面的页面源码。
  1. data = {
  2. 'catalogNodeId': 439,
  3. 'pageNumber': 2,
  4. 'querySortBySign': 0,
  5. 'showOutSockProduct': 1,
  6. 'showDiscountProduct': 1,
  7. 'queryBeginPrice':'',
  8. 'queryEndPrice':'' ,
  9. 'queryProductArrange':'',
  10. 'queryProductGradePlateId': '',
  11. 'queryProductTypeCode': '',
  12. 'queryParameterValue': '',
  13. 'queryProductStandard': '',
  14. 'querySmtLabel': '',
  15. 'queryReferenceEncap': '',
  16. 'queryProductLabel':'',
  17. 'lastParamName': '',
  18. 'baseParameterCondition': '',
  19. 'parameterCondition': ''
  20. }
  21. session = requests.session()
  22. response = session.post(lit_url,data = json.dumps(data),headers = headers).content.decode('utf-8')
复制代码
完整代码如下:
  1. import requests
  2. from lxml import etree
  3. import json
  4. import pandas as pd
  5. import sys


  6. url = 'https://list.szlcsc.com/'

  7. headers = {
  8. 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.34'
  9. }

  10. #获取页面源码
  11. def get_page(url):

  12.     session = requests.session()
  13.     #session在发起请求时会创建cookies,并在下次发起session请求时包含sookies;'.content.decode('utf-8')解决爬取到的数据中文乱码问题'
  14.     page_text = session.get(url = url,headers = headers,proxies=proxy).content.decode('utf-8')
  15.     return page_text

  16. #获取路径下的内容
  17. def get_content(text,path):
  18.     tree = etree.HTML(text)
  19.     content_list = tree.xpath(path)
  20.     return content_list

  21. resp = get_page(url)
  22. for num in range(1,19):
  23.     Manul_list = get_content(resp,f'/html/body/div[1]/div/div[1]/ul/li[{num}]/div/dl/dt/a[1]/text()')  
  24.     Manul = '/'.join(Manul_list)
  25.     print(str(num)+' '+Manul)

  26. #选择需要查询的大类   
  27. choice = input('please select a number you would like to choice:')
  28. lit_list = get_content(resp,f'/html/body/div[1]/div/div[1]/ul/li[{choice}]/div/dl/dd/a[1]/text()')
  29. lit_url_list = get_content(resp,f'/html/body/div[1]/div/div[1]/ul/li[{choice}]/div/dl/dd/a[1]/@href')
  30. lit_dict = {}
  31. for i in range(0,len(lit_list)):
  32.     lit_dict.update({lit_list[i]:lit_url_list[i]})
  33. name_dict = {}
  34. for n in range(1,len(lit_list)+1):
  35.     print(str(n)+' '+lit_list[n-1])
  36.     name_dict.update({n:lit_list[n-1]})

  37. #选择需要查询的具体类型
  38. cho = int(input('please select a number you would like to choice:'))
  39. lit_url = lit_dict[name_dict[cho]]


  40. data = {
  41. 'catalogNodeId': 439,
复制代码
运行代码后选1,然后选18.
得到的却不是我想要的这个页面的页面源码,哪里出现了问题呢?

最佳答案
2022-1-25 09:26:18
看看这些东西是不是你要的,这个页面太专业了,有点看不懂

  1. import requests,json

  2. data = {
  3. 'catalogNodeId': 439,
  4. 'pageNumber': 2,
  5. 'querySortBySign': 0,
  6. 'showOutSockProduct': 1,
  7. 'showDiscountProduct': 1,
  8. 'queryBeginPrice':'',
  9. 'queryEndPrice':'' ,
  10. 'queryProductArrange':'',
  11. 'queryProductGradePlateId': '',
  12. 'queryProductTypeCode': '',
  13. 'queryParameterValue': '',
  14. 'queryProductStandard': '',
  15. 'querySmtLabel': '',
  16. 'queryReferenceEncap': '',
  17. 'queryProductLabel':'',
  18. 'lastParamName': '',
  19. 'baseParameterCondition': '',
  20. 'parameterCondition': ''
  21. }

  22. headers = {
  23. 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.34',
  24. "cookie": "acw_tc=da3dd31c16430728279798128e080b8460c74973023561a97ab6c006d3; SID=471d893b-2380-43e5-ba2f-7c8cf55e7592; SID.sig=bPEGcnKdLpFDiL5G5xuKHDFqRnS7DjKR0uoun7RX0Cg; Qs_lvt_290854=1643072833; Qs_pv_290854=4487896694418019300; cpx=1; guidePage=true; noLoginCustomerFlag=929acea54e81e00b7866; noLoginCustomerFlag2=a0c9da953af694050bd3; PRO_NEW_SID=8920f7cd-dc56-4f97-bd00-f3cb9b98596b; computerKey=d87e0a87824fc7096b6a; AGL_USER_ID=85617b33-f9fb-4d6e-9d65-1b1878037a9d; Hm_lvt_e2986f4b6753d376004696a1628713d2=1643072840; Hm_lpvt_e2986f4b6753d376004696a1628713d2=1643072840; show_out_sock_product=1",
  25. "origin":"https://list.szlcsc.com",
  26. "referer": "https://list.szlcsc.com/catalog/439.html"
  27. }

  28. url="https://list.szlcsc.com/products/list"

  29. txt=requests.post(url,headers=headers,data=data).text
  30. js=json.loads(txt)
  31. print(js["productRecordList"])
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2022-1-25 09:26:18 | 显示全部楼层    本楼为最佳答案   
看看这些东西是不是你要的,这个页面太专业了,有点看不懂

  1. import requests,json

  2. data = {
  3. 'catalogNodeId': 439,
  4. 'pageNumber': 2,
  5. 'querySortBySign': 0,
  6. 'showOutSockProduct': 1,
  7. 'showDiscountProduct': 1,
  8. 'queryBeginPrice':'',
  9. 'queryEndPrice':'' ,
  10. 'queryProductArrange':'',
  11. 'queryProductGradePlateId': '',
  12. 'queryProductTypeCode': '',
  13. 'queryParameterValue': '',
  14. 'queryProductStandard': '',
  15. 'querySmtLabel': '',
  16. 'queryReferenceEncap': '',
  17. 'queryProductLabel':'',
  18. 'lastParamName': '',
  19. 'baseParameterCondition': '',
  20. 'parameterCondition': ''
  21. }

  22. headers = {
  23. 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.34',
  24. "cookie": "acw_tc=da3dd31c16430728279798128e080b8460c74973023561a97ab6c006d3; SID=471d893b-2380-43e5-ba2f-7c8cf55e7592; SID.sig=bPEGcnKdLpFDiL5G5xuKHDFqRnS7DjKR0uoun7RX0Cg; Qs_lvt_290854=1643072833; Qs_pv_290854=4487896694418019300; cpx=1; guidePage=true; noLoginCustomerFlag=929acea54e81e00b7866; noLoginCustomerFlag2=a0c9da953af694050bd3; PRO_NEW_SID=8920f7cd-dc56-4f97-bd00-f3cb9b98596b; computerKey=d87e0a87824fc7096b6a; AGL_USER_ID=85617b33-f9fb-4d6e-9d65-1b1878037a9d; Hm_lvt_e2986f4b6753d376004696a1628713d2=1643072840; Hm_lpvt_e2986f4b6753d376004696a1628713d2=1643072840; show_out_sock_product=1",
  25. "origin":"https://list.szlcsc.com",
  26. "referer": "https://list.szlcsc.com/catalog/439.html"
  27. }

  28. url="https://list.szlcsc.com/products/list"

  29. txt=requests.post(url,headers=headers,data=data).text
  30. js=json.loads(txt)
  31. print(js["productRecordList"])
复制代码
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2022-1-25 10:21:54 | 显示全部楼层
wp231957 发表于 2022-1-25 09:26
看看这些东西是不是你要的,这个页面太专业了,有点看不懂

所以这些产品的一些信息都是在返回的json串中是吗?
‘origin’和·‘referer’是一定要的吗?
非常感谢
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-1-25 10:26:53 | 显示全部楼层
2022@lif 发表于 2022-1-25 10:21
所以这些产品的一些信息都是在返回的json串中是吗?
‘origin’和·‘referer’是一定要的吗?
非常感 ...

‘origin’和·‘referer’是一定要的吗?
这个需要一个一个的测试,我图方便 全都放上去了,我也不知道是否全部必须,感觉上COOKIE是必须


所以这些产品的一些信息都是在返回的json串中是吗?

是的,这个请求返回的是一个json串,而不是一个页面
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-1-25 10:32:36 | 显示全部楼层
wp231957 发表于 2022-1-25 10:26
‘origin’和·‘referer’是一定要的吗?
这个需要一个一个的测试,我图方便 全都放上去了,我也不知道 ...

那是需要用字典和列表的方式来对json串进行处理从而来得到我想要的数据吗?
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-1-25 10:35:08 From FishC Mobile | 显示全部楼层
2022@lif 发表于 2022-1-25 10:32
那是需要用字典和列表的方式来对json串进行处理从而来得到我想要的数据吗?

是的,看返回数据类型,有时候是列表(js中叫数组)有时候是字典(js中叫json串)
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

 楼主| 发表于 2022-1-25 10:39:30 | 显示全部楼层
wp231957 发表于 2022-1-25 10:35
是的,看返回数据类型,有时候是列表(js中叫数组)有时候是字典(js中叫json串)

txt=requests.post(url,headers=headers,data=data,proxies = proxy).text

这里的data=data不需要用data=json.dumps(data)吗?这个我是在网上看到的,说是将 Python 对象编码成JSON字符串。我也不是很清楚
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-1-25 11:02:50 From FishC Mobile | 显示全部楼层
2022@lif 发表于 2022-1-25 10:39
txt=requests.post(url,headers=headers,data=data,proxies = proxy).text

这里的data=data不需要用da ...

一般情况下都不用吧,字典本身就和json都是一个玩意
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 1 反对 0

使用道具 举报

 楼主| 发表于 2022-1-26 08:46:38 | 显示全部楼层
wp231957 发表于 2022-1-25 09:26
看看这些东西是不是你要的,这个页面太专业了,有点看不懂
  1. import requests,json
  2. import pandas as pd
  3. productinformation_list = []
  4. #for i in range(1,7):
  5. data = {
  6. 'catalogNodeId': 11182,
  7. 'pageNumber': 1,
  8. 'querySortBySign': 0,
  9. 'showOutSockProduct': 1,
  10. 'showDiscountProduct': 1,
  11. 'queryBeginPrice':'',
  12. 'queryEndPrice':'' ,
  13. 'queryProductArrange':'',
  14. 'queryProductGradePlateId': '',
  15. 'queryProductTypeCode': '',
  16. 'queryParameterValue': '',
  17. 'queryProductStandard': '',
  18. 'querySmtLabel': '',
  19. 'queryReferenceEncap': '',
  20. 'queryProductLabel':'',
  21. 'lastParamName': '',
  22. 'baseParameterCondition': '',
  23. 'parameterCondition': ''
  24. }

  25. headers = {
  26. 'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36 Edg/96.0.1054.34',
  27. "cookie": "acw_tc=da3dd31c16430728279798128e080b8460c74973023561a97ab6c006d3; SID=471d893b-2380-43e5-ba2f-7c8cf55e7592; SID.sig=bPEGcnKdLpFDiL5G5xuKHDFqRnS7DjKR0uoun7RX0Cg; Qs_lvt_290854=1643072833; Qs_pv_290854=4487896694418019300; cpx=1; guidePage=true; noLoginCustomerFlag=929acea54e81e00b7866; noLoginCustomerFlag2=a0c9da953af694050bd3; PRO_NEW_SID=8920f7cd-dc56-4f97-bd00-f3cb9b98596b; computerKey=d87e0a87824fc7096b6a; AGL_USER_ID=85617b33-f9fb-4d6e-9d65-1b1878037a9d; Hm_lvt_e2986f4b6753d376004696a1628713d2=1643072840; Hm_lpvt_e2986f4b6753d376004696a1628713d2=1643072840; show_out_sock_product=1",
  28. "origin":"https://list.szlcsc.com",
  29. "referer": "https://list.szlcsc.com/catalog/11182.html"
  30. }

  31. url="https://list.szlcsc.com/products/list"

  32. txt=requests.post(url,headers=headers,data=data).text
  33. js=json.loads(txt)

  34. #详情页的数据处理
  35. product_list = js["productRecordList"]
  36. print(product_list)
  37. for n in range(0,len(product_list)):
  38.     product_dict = product_list[n]
  39.     productinformation = []
  40.     productName = product_dict['productName']        #产品名
  41.     productinformation.append(productName)
  42.     productCode = product_dict['productCode']        #产品编号
  43.     productinformation.append(productCode)
  44.     productModel = product_dict["productModel"]      #产品型号
  45.     productinformation.append(productModel)
  46.     package = product_dict['encapsulationModel']     #产品封装
  47.     productinformation.append(package)
  48.     brandname = product_dict['lightBrandName']       #产品品牌
  49.     productinformation.append(brandname)
  50.     packageArrange = product_dict['productArrange']  #产品包装
  51.     productinformation.append(packageArrange)
  52.     gdWarehouseStockNumber = product_dict['gdWarehouseStockNumber']
  53.     productinformation.append(gdWarehouseStockNumber)
  54.     jsWarehouseStockNumber = product_dict['jsWarehouseStockNumber']
  55.     productinformation.append(jsWarehouseStockNumber)

  56.     #产品价格数据处理
  57.     #内地(人民币)
  58.     productprice_list = product_dict["productPriceList"]
  59.     Num1 = ''
  60.     for price in productprice_list:
  61.         Num1 = Num1+str(price['spNumber'])+'->'+str(price['epNumber'])+':¥'+str(price['thePrice'])+'\n'
  62.     productinformation.append(Num1)
  63.     #香港(美元)
  64.     productprice_list = product_dict["productHkDollerPriceList"]
  65.     Num2 = ''
  66.     for price in productprice_list:
  67.         Num2 = Num2+str(price['spNumber'])+'->'+str(price['epNumber'])+':$'+str(price['thePrice'])+'\n'
  68.     productinformation.append(Num2)
  69.    
  70.     productinformation_list.append(productinformation)

  71. lable = ['产品名','产品编号','产品型号','产品封装','产品品牌','产品包装','广东存储量','江苏存储量','内地(RMB)/个','香港(美元)/个']
  72. text = pd.DataFrame(productinformation_list,columns = lable)
  73. text.to_csv('./1-25.csv',encoding='utf-8')
  74. print('OK')
复制代码


当pageNumber为1的时候运行代码,显示在68行那里报错,说keyError: 'productHkDollerPriceList'。但是我将获得的product_list打印出来,搜索是有 'productHkDollerPriceList'这个字段的。
这是什么原因啊?‘productPriceList’这个字段就不会报错。
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2022-1-26 13:33:37 | 显示全部楼层
2022@lif 发表于 2022-1-26 08:46
当pageNumber为1的时候运行代码,显示在68行那里报错,说keyError: 'productHkDollerPriceList'。但 ...

确实没有看到你这个 productHkDollerPriceList  东东
图层 2js.png
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

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

本版积分规则

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

GMT+8, 2025-4-30 10:09

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

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