无法使用python urllib解析Google标题

时间:2019-11-02 15:46:00

标签: python python-3.x urllib

我无法解析Gooogle搜索结果:

def extracter(url,key,change):
    if " " in key:
        key=key.replace(" ",str(change))
    url=url+str(key)
    response=ur.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
    sauce =ur.urlopen(response).read()
    soup=bs(sauce,"html.parser")
    return soup    

def google(keyword):
    soup = extracter("https://www.google.com/search?q=",str(keyword),"+")
    search_result = soup.findAll("h3",attrs={"class":"LC20lb"})
    print(search_result)
google("tony stark")

输出:

[]

1 个答案:

答案 0 :(得分:1)

我只是更改了标题,它就起作用了:

headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36'}

结果:

[<h3 class="LC20lb"><span dir="ltr">Tony Stark (Marvel Cinematic Universe) - Wikipedia</span></h3>, <h3 class="LC20lb"><span dir="ltr">Tony Stark / Iron Man - Wikipedia</span></h3>, <h3 class="LC20lb"><span dir="ltr">Iron Man | Marvel Cinematic Universe Wiki | FANDOM ...</span></h3>, <h3 class="LC20lb"><span dir="ltr">Tony Stark (Earth-199999) | Iron Man Wiki | FANDOM ...</span></h3>, <h3 class="LC20lb"><span dir="ltr">Is Tony Stark Alive As AI? Marvel Fans Say Tony Stark ...</span></h3>, <h3 class="LC20lb"><span dir="ltr">'Avengers: Endgame' Might Not Have Been the End of Tony ...</span></h3>, <h3 class="LC20lb"><span dir="ltr">Robert Downey Jr to RETURN to MCU as AI Tony Stark - ...</span></h3>, <h3 class="LC20lb"><span dir="ltr">Avengers Endgame theory: Tony Stark is backed up as AI ...</span></h3>]