确保您使用的是最新的user-agent
. Olduser-agents
是向网站发出的信号,表明它可能是发送请求的机器人。但是一个新的user-agent
并不意味着每个网站都会认为这是一个“真正的”用户访问。检查你的user-agent
.
代码片段使用parsel
类似于bs4
但它支持完整 XPath 的库,并使用包将每个 CSS 选择器查询转换为 XPathcssselect
。
要集成的示例代码:
from collections import namedtuple
import requests
from parsel import Selector
# https://docs.python-requests.org/en/master/user/quickstart/#passing-parameters-in-urls
params = {
"user": "VGoSakQAAAAJ",
"hl": "en",
"view_op": "citations_histogram"
}
# https://docs.python-requests.org/en/master/user/quickstart/#custom-headers
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.87 Safari/537.36",
}
html = requests.get("https://scholar.google.com/citations", params=params, headers=headers, timeout=30)
selector = Selector(html.text)
Publications = namedtuple("Years", "first_publication")
publications = Publications(sorted([publication.get() for publication in selector.css(".gsc_g_t::text")])[0])
print(selector.css(".gsc_g_t::text").get())
print(sorted([publication.get() for publication in selector.css(".gsc_g_t::text")])[0])
print(publications.first_publication)
# output:
'''
1996
1996
1996
'''
或者,您可以使用来自 SerpApi的Google Scholar Author API来实现相同的目的。这是一个带有免费计划的付费 API。
不同之处在于您不必弄清楚如何解析数据并随着时间的推移维护解析器,弄清楚如何扩展它,并绕过搜索引擎(例如 Google Scholar 搜索引擎)的块。
要集成的示例代码:
from serpapi import GoogleScholarSearch
params = {
"api_key": "Your SerpApi API key",
"engine": "google_scholar_author",
"hl": "en",
"author_id": "VGoSakQAAAAJ"
}
search = GoogleScholarSearch(params)
results = search.get_dict()
# already sorted data
first_publication = [year.get("year") for year in results.get("cited_by", {}).get("graph", [])][0]
print(first_publication)
# 1996
如果你想根据给定的查询抓取所有个人资料结果,或者你有一个作者 ID 列表,有一个专门的抓取所有谷歌学术个人资料,作者结果到我的 CSV 博客文章。
免责声明,我为 SerpApi 工作。