国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Python > 正文

Python實現抓取百度搜索結果頁的網站標題信息

2019-11-25 18:01:33
字體:
來源:轉載
供稿:網友

比如,你想采集標題中包含“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))

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 双鸭山市| 斗六市| 永登县| 丰原市| 雷州市| 偃师市| 龙门县| 孟津县| 儋州市| 吉木萨尔县| 乌鲁木齐市| 黄平县| 三穗县| 沁阳市| 招远市| 韶关市| 龙游县| 孟村| 凤冈县| 马山县| 平利县| 西充县| 定西市| 泽州县| 当涂县| 商丘市| 锡林浩特市| 吴桥县| 裕民县| 拉孜县| 广德县| 香河县| 古浪县| 凤山县| 双鸭山市| 瓮安县| 丹巴县| 荥经县| 富宁县| 新竹县| 迭部县|