代码之家  ›  专栏  ›  技术社区  ›  maurobio

用python和beautifulsoup解析google学者的结果

  •  4
  • maurobio  · 技术社区  · 8 年前

    给定一个典型的谷歌学者关键词搜索(见截图),我想得到一个包含 标题 网址 出现在页面上的每个出版物(例如 results = {'title': 'Cytosolic calcium regulates ion channels in the plasma membrane of Vicia faba guard cells', 'url': 'https://www.nature.com/articles/338427a0' }。

    enter image description here

    要从Google奖学金获得结果页面,我使用以下代码:

    from urllib import FancyURLopener, quote_plus
    from bs4 import BeautifulSoup
    
    class AppURLOpener(FancyURLopener):
        version = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.152 Safari/537.36'
    
    openurl = AppURLOpener().open
    query = "Vicia faba"
    url = 'https://scholar.google.com/scholar?q=' + quote_plus(query) + '&ie=UTF-8&oe=UTF-8&hl=en&btnG=Search'
    #print url
    content = openurl(url).read()
    page = BeautifulSoup(content, 'lxml')
    print page
    

    此代码以(非常难看的)HTML格式正确返回结果页。但是,我还没能超越这一点,因为我不知道如何使用BeautifulSoup(我不太熟悉)来解析结果页和检索数据。

    注意,问题在于分析和提取结果页面中的数据,而不是谷歌学者本身,因为上面的代码正确地检索到了结果页面。

    有人能给点提示吗?事先谢谢!

    1 回复  |  直到 8 年前
        1
  •  6
  •   andrew_reece    8 年前

    检查页面内容显示搜索结果包装在 h3 标签,带属性 class="gs_rt" . 您可以使用BeautifulSoup提取这些标签,然后从 <a> 在每个条目内标记。将每个标题/URL写入dict,并存储在dict列表中:

    import requests
    from bs4 import BeautifulSoup
    
    query = "Vicia%20faba"
    url = 'https://scholar.google.com/scholar?q=' + query + '&ie=UTF-8&oe=UTF-8&hl=en&btnG=Search'
    
    content = requests.get(url).text
    page = BeautifulSoup(content, 'lxml')
    results = []
    for entry in page.find_all("h3", attrs={"class": "gs_rt"}):
        results.append({"title": entry.a.text, "url": entry.a['href']})
    

    输出:

    [{'title': 'Cytosolic calcium regulates ion channels in the plasma membrane of Vicia faba guard cells',
      'url': 'https://www.nature.com/articles/338427a0'},
     {'title': 'Hydrogen peroxide is involved in abscisic acid-induced stomatal closure in Vicia faba',
      'url': 'http://www.plantphysiol.org/content/126/4/1438.short'},
     ...]
    

    注:我用过 requests 而不是 urllib ,作为我的 小精灵 无法加载 FancyURLopener . 但是不管如何获得页面内容,漂亮的汤语法应该是相同的。