0

我有下面的简单脚本,它可以很好地从 Google Scholar 中获取文章列表以搜索感兴趣的术语。

import urllib
import urllib2
import requests
from bs4 import BeautifulSoup

SEARCH_SCHOLAR_HOST = "https://scholar.google.com"
SEARCH_SCHOLAR_URL = "/scholar"

def searchScholar(searchStr, limit=10):
    """Search Google Scholar for articles and publications containing terms of interest"""
    url = SEARCH_SCHOLAR_HOST + SEARCH_SCHOLAR_URL + "?q=" + urllib.quote_plus(searchStr) + "&ie=UTF-8&oe=UTF-8&hl=en&btnG=Search"
    content = requests.get(url, verify=False).text
    page = BeautifulSoup(content, 'lxml')
    results = {}
    count = 0
    for entry in page.find_all("h3", attrs={"class": "gs_rt"}):
        if count < limit:
            try:
                text = entry.a.text.encode("ascii", "ignore")
                url = entry.a['href']
                results[url] = text 
                count += 1
            except:
                pass
    return results

queryStr = "Albert einstein"
pubs = searchScholar(queryStr, 10)
if len(pubs) == 0:
    print "No articles found"
else:   
    for pub in pubs.keys():
        print pub + ' ' + pubs[pub]

但是,我想在远程服务器上将此脚本作为 CGI 应用程序运行,而无需访问控制台,因此我无法安装任何外部 Python 模块。(我设法通过将 bs4 目录复制到我的 cgi-bin 目录而无需借助 pip 或 easy_install 来“安装”BeautifulSoup,但由于其大量依赖项,此技巧不适用于请求。)

所以,我的问题是:是否可以使用内置的 urllib2 或 httplib Python 模块,而不是请求获取 Google Scholar 页面,然后将其传递给 BeautifulSoup?应该是,因为我在这里找到了一些代码,它只使用标准库和 BeautifulSoup 来抓取 Google Scholar,但它相当复杂。我宁愿实现一个更简单的解决方案,只是调整我的脚本以使用标准库而不是请求。

谁能给我一些帮助?

4

1 回答 1

1

这段代码足以使用urllib2执行一个简单的请求:

def get(url):
    req = urllib2.Request(url)
    req.add_header('User-Agent', 'Mozilla/2.0 (compatible; MSIE 5.5; Windows NT)')
    return urllib2.urlopen(req).read()

如果您将来需要做一些更高级的事情,那将是更多的代码。request 的作用是简化标准库的使用。

于 2019-01-30T20:34:42.617 回答