Python实现抓取百度搜索结果页的网站标题信息

Doris ·
更新时间:2024-09-21
· 894 次阅读

比如,你想采集标题中包含“58同城”的SERP结果,并过滤包含有“北京”或“厦门”等结果数据。

该Python脚本主要是实现以上功能。

其中,使用BeautifulSoup来解析HTML,可以参考我的另外一篇文章:Windows8下安装BeautifulSoup

代码如下:

代码如下:
__author__ = '曾是土木人'
# -*- coding: utf-8 -*-
#采集SERP搜索结果标题
import urllib2
from bs4 import BeautifulSoup
import time
#写文件
def WriteFile(fileName,content):
    try:
        fp = file(fileName,"a+")
        fp.write(content + "\r")
        fp.close()
    except:
        pass

#获取Html源码
def GetHtml(url):
    try:
        req = urllib2.Request(url)
        response= urllib2.urlopen(req,None,3)#设置超时时间
        data    = response.read().decode('utf-8','ignore')
    except:pass
    return data

#提取搜索结果SERP的标题
def FetchTitle(html):
    try:
        soup = BeautifulSoup(''.join(html))
        for i in soup.findAll("h3"):
            title = i.text.encode("utf-8")      
       if any(str_ in title for str_ in ("北京","厦门")):
          continue
            else:
                print title
            WriteFile("Result.txt",title)
    except:
        pass

keyword = "58同城"
if __name__ == "__main__":
    global keyword
    start = time.time()
    for i in range(0,8):
        url = "http://www.baidu.com/s?wd=intitle:"+keyword+"&rn=100&pn="+str(i*100)
        html = GetHtml(url)
        FetchTitle(html)
        time.sleep(1)
    c = time.time() - start
    print('程序运行耗时:%0.2f 秒'%(c))

您可能感兴趣的文章:Python多进程入门、分布式进程数据共享实例详解Python2.7实现多进程下开发多线程示例Python实现的服务器示例小结【单进程、多进程、多线程、非阻塞式】Python多进程并发(multiprocessing)用法实例详解浅析Python中的多进程与多线程的使用探究Python多进程编程下线程之间变量的共享问题Python控制多进程与多线程并发数总结Python多线程、异步+多进程爬虫实现代码Python学习笔记之抓取某只基金历史净值数据实战案例Python使用代理抓取网站图片(多线程)Python多进程方式抓取基金网站内容的方法分析



百度搜索 Python

需要 登录 后方可回复, 如果你还没有账号请 注册新账号