python實現提取百度搜尋結果的方法

來源:互聯網
上載者:User
本文執行個體講述了python實現提取百度搜尋結果的方法。分享給大家供大家參考。具體實現方法如下:

# coding=utf8import urllib2import stringimport urllibimport reimport random#設定多個user_agents,防止百度限制IPuser_agents = ['Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20130406 Firefox/23.0', \    'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:18.0) Gecko/20100101 Firefox/18.0', \    'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533+ \    (KHTML, like Gecko) Element Browser 5.0', \    'IBM WebExplorer /v0.94', 'Galaxy/1.0 [en] (Mac OS X 10.5.6; U; en)', \    'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0)', \    'Opera/9.80 (Windows NT 6.0) Presto/2.12.388 Version/12.14', \    'Mozilla/5.0 (iPad; CPU OS 6_0 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) \    Version/6.0 Mobile/10A5355d Safari/8536.25', \    'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) \    Chrome/28.0.1468.0 Safari/537.36', \    'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0; TheWorld)']def baidu_search(keyword,pn):  p= {'wd': keyword}   res=urllib2.urlopen(("http://www.baidu.com/s?"+urllib.urlencode(p)+"&pn={0}&cl=3&rn=100").format(pn))  html=res.read()  return htmldef getList(regex,text):  arr = []  res = re.findall(regex, text)  if res:    for r in res:      arr.append(r)  return arrdef getMatch(regex,text):  res = re.findall(regex, text)  if res:    return res[0]  return ""def clearTag(text):  p = re.compile(u'<[^>]+>')  retval = p.sub("",text)  return retvaldef geturl(keyword):  for page in range(10):    pn=page*100+1    html = baidu_search(keyword,pn)    content = unicode(html, 'utf-8','ignore')    arrList = getList(u".*?<\/a>", content)    for item in arrList:      regex = u"(.*?)<\/a>"      link = getMatch(regex,item)      url = link[0]      #擷取標題      #title = clearTag(link[1]).encode('utf8')      try:        domain=urllib2.Request(url)        r=random.randint(0,11)        domain.add_header('User-agent', user_agents[r])        domain.add_header('connection','keep-alive')        response=urllib2.urlopen(domain)        uri=response.geturl()        print uri      except:        continueif __name__=='__main__':  geturl('python')

希望本文所述對大家的Python程式設計有所協助。

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.