已有excel表格,表格含有一列待搜索关键字,如下:
查阅得知使用xlwt、xlrd两个python库分别完成xls文件的写入和读出。
首先读出该表格对应那列关键字,编码方式使用utf-8,防止乱码,此时,用全局变量暂时存储所有关键字
excel_path = "/mnt/hgfs/share/brand.xls"
excel = xlrd.open_workbook(excel_path, encoding_override="utf-8")
# 获取对应工作表
sheet = excel.sheet_by_index(0)
# 获取关键字那一列
brand_list = sheet.col(0)
使用scrapy爬虫框架,第一级方法提交对应的搜索页面url,下一级方法用xpath定位返回的url,通过正则表达式匹配首页的url,其中域名含有关键字的写入对应关键字旁一列,如此直到关键字搜索完毕。
第一级方法中将对应关键字传入第二级方法中便于筛选,如下
request = scrapy.Request(url, meta={'brand': brand}, callback=self.parse_list)
正则表达式匹配关键字是否在url域名中,如下
# ://任意字符(任意次)+列表获得的品牌名(一次)+任意字符(任意次)+.+数字或字母(一次)+/
demo = re.findall(r'://.*%s.*\.[\w]*/' % brand, address, re.I)
以下为整个脚本:
# -*- coding:utf-8 -*-
__author__ = "xiaoqun"
__time__ = "2020.05.31"
''' '''
import time
import re
import scrapy
from scrapy.spiders import Spider
import testdemo.items as MI
import xlrd
import xlwt
from xlutils.copy import copy
excel_path = "/mnt/hgfs/share/brand.xls"
# 打开文件,获取excel文件的workbook(工作簿)对象
excel = xlrd.open_workbook(excel_path, encoding_override="utf-8")
# 获取sheet对象
sheet = excel.sheet_by_index(0)
te = '/mnt/hgfs/share/brand'
te = te.replace('/', '_')
sheet.name = te
# 获取表格第一列所有单元格内容
brand_list = sheet.col(0)
# 完成xlrd对象向xlwt对象转换
excel_wr = copy(wb=excel)
excel_table = excel_wr.get_sheet(0)
# for brand in brand_list:
class TwitterbotSpider(Spider):
name = "Twitterbot"
start_urls = [
"https://cn.bing.com/"
]
allsuffix = set()
timeout = 20
trytimes = 3
headurl = "https://cn.bing.com/"
def parse(self, response):
for brand in brand_list:
# 将品牌列表的各个厂商名加到必应搜索url中
url = self.headurl + 'search?q={}+firmware'.format(brand.value)
# 使用request的meta参数将当前迭代的品牌名传递至下一个函数做筛选
request = scrapy.Request(url, meta={'brand': brand}, callback=self.parse_list)
yield request
def parse_list(self, response):
# 获取搜索反馈页面的所有url
url_lis = response.xpath('//*[@id="b_results"]/li//h2/a/@href').extract()
for address in url_lis:
# 得到此时对应的品牌名
info = response.meta['brand']
brand = info.value
# 匹配url的域名字符串中是否含有品牌名
# demo = re.findall(r'://.*(%s).*/^' % brand, address, re.I)
# ://任意字符(任意次)+列表获得的品牌名(一次)+任意字符(任意次)+.+数字或字母(一次)+/
demo = re.findall(r'://.*%s.*\.[\w]*/' % brand, address, re.I)
if demo:
i = brand_list.index(info)
print('the url found was :', address)
excel_table.write(i, 1, address)
yield excel_wr.save('/mnt/hgfs/share/brand.xls')
print(sheet.cell(i, 1).value)