sys,webbrowser

import requests,bs4,pyperclip,sys,webbrowser
from bs4 import BeautifulSoup

start_url='http://www.baidu.com/s?wd='

def getWord():
    if len(sys.argv) >1 :
        return sys.argv[1]
    else:
        return pyperclip.paste()

def getHTMLText(word='百度'):
    try:
        res = requests.get(start_url+word)
        res.raise_for_status()
        res.encoding = res.apparent_encoding
        #print(res.text)
        return res.text
    except Exception as e:
        print("%s"%e)

def openURL(html):
    links = []
    soup = BeautifulSoup(html,'html.parser')
    divs = soup.findAll('div',attrs={'id':'content_left'})
    for div in divs:
        links.append(div.a.attrs.get('href'))
    numOpen = min(5,len(links))
    for i in range(numOpen):
        print(links[i])
        webbrowser.open(links[i])

def main():
    keyWord = getWord()
    html = getHTMLText(keyWord)
    openURL(html)

main()


你可能感兴趣的:(sys,webbrowser)