爬取目标
我们要爬取的网页是:
http://www.mp.cc/search/1?category=25
网站主页如下:
1)第一页有39个商标展示,每一个都需要进入网页获取详细信息(未截图完)
红色框就是要爬取的内容
2)一共91页
给你们看看我爬取完的效果,保存在SqlServer中:
爬取的内容是:商标名、商标价格、商标编号、所属类别、专用期限、类似群组、注册范围、商标图片地址
准备工作
我用的是python3.8,VScode编辑器,所需的库有:requests、etree、pymssql
开头导入所需用到的导入的库:
import requests # python基础爬虫库
from lxml import etree # 可以将网页转换为Elements对象
import pymssql # 连接SqlServer的库
建表:
CREATE TABLE "MPSB" (
"title" NVARCHAR(MAX),
"price" NVARCHAR(MAX),
"number" NVARCHAR(MAX),
"category" NVARCHAR(MAX),
"term" NVARCHAR(MAX),
"groups" NVARCHAR(MAX),
"Range" NVARCHAR(MAX),
"img_url" NVARCHAR(MAX)
)
为防止,字段给的不够,直接给个MAX!
代码分析
直接上完整代码,再逐步分析!
import requests # python基础爬虫库
from lxml import etree # 可以将网页转换为
import pymssql # 连接SqlServer的库
import time
class TrademarkSpider:
def __init__(self) :
self.baseurl = "http://www.mp.cc/search/%s?category=%s"
self.headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"}
# 发送请求,获取相应
def parse_url(self,url):
response = requests.get(url,headers=self.headers)
time.sleep(2)
return response.content.decode()
# 获取每种类别主页个数
def get_page_num(self,html_str):
html = etree.HTML(html_str)
div_list = html.xpath("//div[@class='pagination']") # 根据div分组
try:
for div in div_list:
a = div.xpath("//a[@class='number']/text()")
index = len(a)-1
page = int(a[index])
except:
page = 1
print(page,'页')
return page
# 获取每页中n个详情页地址
def get_content_list(self,html_str):
html = etree.HTML(html_str)
div_list = html.xpath("//div[@class='item_wrapper']") # 根据div分组
item = {}
for div in div_list:
item["href"]= div.xpath("//a[@class='img-container']/@href")
# 获取每页中详情页个数
html1 = etree.HTML(html_str)
div_list1 = html1.xpath("//div[@class='item_wrapper']") # 根据div分组
detailed_num = len(div_list1)
print(detailed_num)
# 拼接网页
for i in range(0,detailed_num):
item["href"][i] = 'http://www.mp.cc%s' % item["href"][i]
for value in item.values():
content_list = value
#print(content_list)
return content_list
# 获取1-n(n最大为39)个详情页信息
def get_information(self,content_list):
information = []
for i in range(len(content_list)):
details_url = content_list[i]
html_str = self.parse_url(details_url)
html = etree.HTML(html_str)
div_list = html.xpath("//div[@class='d_top']") # 根据div分组
item = []
for div in div_list:
title = div.xpath("///div[@class='d_top_rt_right']/text()")
price = div.xpath("//div[@class='text price2box']/span[2]/text()")
number = div.xpath("//div[@class='text'][1]/text()")
category = div.xpath("//div[@class='text'][2]/span[@class='cate']/text()")
term = div.xpath("//div[@class='text'][3]/tex