接着上篇记录的爬虫应用,这次来试下百度搜索的爬虫应用。百度的很多搜索结果可以为我们的行业挣得信息差,并且统计数据后可以发现规律,根据规律寻找盈利点。所以我们先来试下小demo来尝试爬取百度的搜索结果。
def start_requests(self):
urls = [
# 关键词为python入门到放弃
"http://www.baidu.com/s?ie=UTF-8&wd=python%E5%85%A5%E9%97%A8%E5%88%B0%E6%94%BE%E5%BC%83"
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
"""
用css表达式拿到目标网页元素
将其解析后提交到pipelines进行持久化
"""
title_list = response.css("div.result h3 a").extract()
desc_list = response.css("div.result span[class*='right']").extract()
source_list = response.css("div[class*='source'] span.c-color-gray::text").extract()
for index, a in enumerate(title_list):
title = ''.join(Selector(text=title_list[index]).css(
"::text").extract())
href = Selector(text=title_list[index]).css(
"::attr(href)").extract_first()
desc = ''.join(Selector(text=desc_list[index]).css(
"::text").extract())
source = source_list[index]
item = BaiduSearchSpiderItem()
item["title"] = title
item["href"] = href
item["desc"] = desc
item["source"] = source
yield item
# 机器人协议要设置为否
ROBOTSTXT_OBEY = False
# 指定pipelines中间件,不然不会进入到持久化层
ITEM_PIPELINES = {
'baidu_search_spider.pipelines.BaiduSearchSpiderPipeline': 300,
}
# 设置默认请求头
DEFAULT_REQUEST_HEADERS = {
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Language': 'en',
}
def process_item(self, item, spider):
"""
接收到提交过来的对象后,写入csv文件
"""
filename = f'baidu_search_result.csv'
with open(filename, 'a+', encoding='utf-8') as f:
line = item["title"].replace(",", ",") + "," + item["href"] + "," + item["desc"].replace(",", ",") + "," + item[
"source"] + "\n"
f.write(line)
# self.log(f'Saved file {filename}')
return item
对于百度这种网站来说,这种请求如果访问频繁容易进入安全检测环节,这里也只是初次测试。要想将这种需求落实下来,我们要改进为用selenium去模拟人工操作浏览器进行爬取。接下来会跟着这个思路去实现。