百度搜索引擎和必应搜索引擎搜索内容简单爬取Python

这个博客用于记录我的计算机学习的路途,本文用于记录Python百度搜索爬虫编写过程。

第一步 本程序所用的python库

1,requests 用于GET网页返回的信息,这个库比较重要。可以用来模拟浏览器的GET和POST,伪装浏览器,成功爬取内容。比起urllib和urllib2要有很大的简便性。

2,lxml中的etree可以通过xpath获取爬取到的内容的特定部分。配合chrome使用会更好(chrome中有自带的可以获取xpath的工具。)

第二步 设计爬虫伪装浏览器

1,以下是一个头的简单示例。

    headers = {
        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate, compress',
        'Accept-Language': 'en-us;q=0.5,en;q=0.3',
        'Cache-Control': 'max-age=0',
        'Connection': 'keep-alive',
        'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100101 Firefox/22.0'
        }

2,可以获取代理IP(我没有用)

第三步 观察百度搜索的url,获取最初的url(word为要搜索的关键词)

    baiduurl = 'http://www.baidu.com'
    url = 'http://www.baidu.com.cn/s?wd=' + word + '&cl=3'


第四步 爬取内容并解析

    html = requests.get(url=url,headers=headers)
    path = etree.HTML(html.content)


下面是抓取部分代码

        for i in range(1, flag):
            sentence = ""
            for j in path.xpath('//*[@id="%d"]/h3/a//text()'%((k-1)*10+i)):
                sentence+=j
            print sentence
            list.append(sentence)



谢谢大家

【github传送门1 百度爬虫】https://github.com/gongpx20069/BaiduSpider

【github传送门2 Bing爬虫】https://github.com/gongpx20069/BingSpider

你可能感兴趣的:(python爬虫学习)