【问题标题】:extract text from google scholar从谷歌学者中提取文本
【发布时间】:2013-04-02 15:48:33
【问题描述】:

我正在尝试从谷歌学者为特定查询提供的测试 sn-p 中提取文本。文本 sn-p 是指标题下方的文本(黑色字母)。 目前我正在尝试使用python从html文件中提取它,但它包含很多额外的测试,例如

/div><div class="gs_fl"...等

有没有简单的方法或一些代码可以帮助我在没有这些冗余文本的情况下获取文本。

【问题讨论】:

    标签: python text-mining google-scholar


    【解决方案1】:

    你需要一个 html 解析器:

    import lxml.html
    
    doc = lxml.html.fromstring(html)
    text = doc.xpath('//div[@class="gs_fl"]').text_content()
    

    您可以使用“pip install lxml”安装 lxml,但您需要构建其依赖项,具体取决于您的平台。

    【讨论】:

    • 使用你给定的命令我可以解析整个 html 页面还是每次都必须给出不同的 xpath()?
    • 给我这个错误:- AttributeError: 'list' object has no attribute 'text_content'
    【解决方案2】:

    而且很老,但现在可能是一个相关的问题。使用SelectorGadgets 轻松获取 CSS 选择器。确保您使用的是代理,否则即使您尝试通过 selenium 发出请求,Google 也可能会阻止请求。

    在线IDE中的代码和full example

    from bs4 import BeautifulSoup
    import requests, lxml, os
    
    headers = {
        'User-agent':
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.102 Safari/537.36 Edge/18.19582"
    }
    
    proxies = {
      'http': os.getenv('HTTP_PROXY')
    }
    
    html = requests.get('https://scholar.google.com/scholar?hl=en&as_sdt=0%2C5&q=samsung&oq=', headers=headers, proxies=proxies).text
    soup = BeautifulSoup(html, 'lxml')
    
    for result in soup.select('.gs_ri'):
      snippet = result.select_one('.gs_rs').text
      print(f"Snippet: {snippet}")
    

    部分输出:

    Snippet: Purpose–Extensive research has shown that country‐of‐origin (COO) information significantly affects product evaluations and buying behavior. Yet recently, a competing perspective has emerged suggesting that COO effects have been inflated in prior research …
    

    或者,您可以使用来自 SerpApi 的 Google Scholar Organic Search Results API。这是一个付费 API,可免费试用 5,000 次搜索。

    本质上,它和上面的脚本做同样的事情,除了你不需要考虑如何解决验证码或找到一个好的代理(代理)。

    要集成的代码:

    from serpapi import GoogleSearch
    import os
    
    params = {
      "api_key": os.getenv("API_KEY"),
      "engine": "google_scholar",
      "q": "samsung",
    }
    
    search = GoogleSearch(params)
    results = search.get_dict()
    
    for result in results['organic_results']:
      print(f"Snippet: {result['snippet']}")
    

    部分输出:

    Snippet: Purpose–Extensive research has shown that country‐of‐origin (COO) information significantly affects product evaluations and buying behavior. Yet recently, a competing perspective has emerged suggesting that COO effects have been inflated in prior research …
    

    免责声明,我为 SerpApi 工作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多