好的,所以我想通了。我使用了python的selenium模塊,它創建了一個虛擬瀏覽器,如果你願意的話,它可以讓你執行一些操作,比如點擊鏈接並獲得HTML輸出。在解決這個問題時遇到了另一個問題,那就是頁面必須被加載,否則它只是在彈出的div中返回內容「Loading ...」,所以我使用了Python時間模塊time.sleep(2)
2秒,要加載的內容。然後,我使用BeautifulSoup解析生成的HTML輸出,以找到具有類「gs_citi」的錨標記。然後從錨中拉出href,並將其放入帶有「requests」python模塊的請求中。最後,我將解碼的響應寫入本地文件 - scholar.bib。 https://gist.github.com/guylaor/3eb9e7ff2ac91b7559625262b8a6dd5f
然後通過Python文件簽署允許使用這些指令停止防火牆問題: Add Python to OS X Firewall Options?
以下是我的代碼
我在這裏使用這些說明安裝chromedriver和硒對我的Mac用於生成輸出文件「scholar.bib」:
import os
import time
from selenium import webdriver
from bs4 import BeautifulSoup as soup
import requests as req
# Setup Selenium Chrome Web Driver
chromedriver = "/usr/local/bin/chromedriver"
os.environ["webdriver.chrome.driver"] = chromedriver
driver = webdriver.Chrome(chromedriver)
# Navigate in Chrome to specified page.
driver.get("https://scholar.google.com/scholar?hl=en&q=Sustainability and the measurement of wealth: further reflections")
# Find "Cite" link by looking for anchors that contain "Cite" - second link selected "[1]"
link = driver.find_elements_by_xpath('//a[contains(text(), "' + "Cite" + '")]')[1]
# Click the link
link.click()
print("Waiting for page to load...")
time.sleep(2) # Sleep for 2 seconds
# Get Page source after waiting for 2 seconds of current page in Chrome
source = driver.page_source
# We are done with the driver so quit.
driver.quit()
# Use BeautifulSoup to parse the html source and use "html.parser" as the Parser
soupify = soup(source, 'html.parser')
# Find anchors with the class "gs_citi"
gs_citt = soupify.find('a',{"class":"gs_citi"})
# Get the href attribute of the first anchor found
href = gs_citt['href']
print("Fetching: ", href)
# Instantiate a new requests session
session = req.Session()
# Get the response object of href
content = session.get(href)
# Get the content and then decode() it.
bibtex_html = content.content.decode()
# Write the decoded data to a file named scholar.bib
with open("scholar.bib","w") as file:
file.writelines(bibtex_html)
希望這有助於任何尋找解決方案的人出。
Scholar.bib文件:要刮
@article{arrow2013sustainability,
title={Sustainability and the measurement of wealth: further reflections},
author={Arrow, Kenneth J and Dasgupta, Partha and Goulder, Lawrence H and Mumford, Kevin J and Oleson, Kirsten},
journal={Environment and Development Economics},
volume={18},
number={4},
pages={504--516},
year={2013},
publisher={Cambridge University Press}
}
不幸的是,'「引用」'彈出窗口是在底層的網頁從'Cite得到''一個事件javascript'。由於Beautifulsoup是一個解析器而不是交互式網頁瀏覽客戶端,因此您可能需要考慮使用'selenium','PhantomJS'或其他工具解決此問題。 – davedwards
我試着用'selenium'來解決它,但是當我嘗試抓取幾個物品時google會被嚇到 –
@downshift你應該添加你的評論作爲答案 – ands