和朋友交流爬虫的时候看到这个网站,朋友说让我试试,昨天乘着心情好,就爬了一下。
我首先分心了一下这个网站,这个网站很有意思,由于自己的能力问题和爱好,没有对权证进行爬取,只是提取了部分商品的信息。
我拿到这个网站的时候,被这些炫酷的笔记本撂到了,可惜买不起,只能对着自己的台湾船的瞎眼屏撸代码。下面正主来了,我在微星主页打开了产品咨询
当然这时候的网络监听器是这样的
其中的post都是你提交的表单返回的东西。也是我们需要的数据在的地方。
直接打开着url 并不能直接得到信息 但是在他的preview里面就是我们需要的数据,这里对浏览行为做了限制。我们需要在头信息里面加上Referer和User-Agent。
然后这个网页就很简单了,翻页可以拼接url,这样这个网站就可以进行爬取了。下面是部分代码,仅供参考,有错误请联系本人
import re
import requests
from bs4 import BeautifulSoup
import time
# url = 'https://cn.msi.com/product_ajax/get_model_list'
def get_product_list(url,page):
data = {
# 'id[]': '655',
# 'id[]': '674',
'id[]': page,
# 'id[]': 656,
#
'product': 'Notebook',
'category': 'notebook',
'msi_official_csrf': 'dd41103177b055dd79f9ff0103805038'
}
headers = {
'Cookie':'msi_mts=[%22Vk9SVEVYLUc2NS02UUYtMDAzQ04=%22%2C%22R1Q4M1ZSLTdSRi0yMDNDTg==%22]; Hm_lvt_e841c9549d025722162d723ec8b628a6=1506596022; Hm_lpvt_e841c9549d025722162d723ec8b628a6=1506596573; msi_official_csrf=dd41103177b055dd79f9ff0103805038; msi_official_site=45541283d9a93cf8f9058e6cd64018310f4eebc0'
,'Referer':'https://cn.msi.com/Laptops',
'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'
}
try:
response = requests.post(url=url,data= data,headers=headers ).text
soup = BeautifulSoup(response,'lxml' )
product_list = soup.find_all(class_='col-lg-3 col-md-3 col-sm-4 col-xs-6 pdbox')
for product in product_list :
pattern = re.compile('<a href="(.*?)">\n<img.*src="(.*?)".*', re.S)
result = re.search(pattern,str(product))
# href = product.find(re.compile("a") )
a = result.groups()[0]
# print(d)
print(a)
dd = requests.get(a,headers ).text
# print(dd.text )
# time.sleep(2)
soup1 = BeautifulSoup(dd,'lxml')
product_text = soup1.find_all(id = 'prod-info')
for i in product_text :
# d = 0
for n in i.find_all('li'):
# with open('art.txt','w',encoding='utf-8') as f:
# f.write(n.text.strip())
print(n.text.strip())
time.sleep(2)
except Exception as e:
print(e)
# a = result.groups()[0]
# dd = requests.get(a,headers)
# print(dd)
# print(product_list )
ID = 0
page = ['655','674','656','1770','1823','1824','1962','1825']
for i in page:
url = 'https://cn.msi.com/product_ajax/get_model_list/%d' % ID
# page = page[i]
a = get_product_list(url,page= page[0])
print(a)
ID += 20