【问题标题】:Scraping Google Scholar with urllib2 instead of requests使用 urllib2 而不是请求抓取 Google Scholar
【发布时间】:2019-01-30 20:13:55
【问题描述】:

我有下面的简单脚本,它可以很好地从 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 目录来“安装”BeautifulSoup,而无需借助 pip 或 easy_install,但由于其大量的依赖关系,此技巧不适用于请求。)

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

谁能帮帮我?

【问题讨论】:

  • 我不建议放弃 Google Scholar,因为它们不允许机器人。你可能会被禁止。

标签: python python-requests google-scholar


【解决方案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 的作用是简化了标准库的使用。

【讨论】:

  • 谢谢,它工作得很好!这就是我需要的。最良好的祝愿。
  • ...但不完全!正如所料,Gugly 在服务器上运行时会阻止代码的执行(在本地运行良好)。
  • @maurobio 可能是验证码,因为你还没有验证你是服务器ip上的人
猜你喜欢
  • 2022-01-02
  • 2012-07-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-10
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多