【问题标题】:Web scraping Google Scholar with Python使用 Python 抓取 Google Scholar 网页
【发布时间】:2022-01-02 00:16:33
【问题描述】:

您好,我需要使用 bs4 或 Selenium 从 Google Scholar 的记录中提取摘要和 DOI。我对这样的“academic.oup”页面有疑问: https://academic.oup.com/eurheartj/article-abstract/42/Supplement_1/ehab724.1650/6394300

我无法使用 bs4 或 selenium 提取 DOI 或摘要。 这是我的硒代码:

driver = webdriver.Chrome('/Users/cante/Downloads/chromedriver_win32/chromedriver.exe')
driver.get('https://academic.oup.com/eurheartj/article-abstract/42/Supplement_1/ehab724.1650/6394300')
abstract = driver.find_elements_by_xpath('//*[@id="ContentTab"]/div[1]/div/div/section')
doi_element = driver.find_elements_by_xpath('//*[@id="ContentColumn"]/div[3]/div[1]/div/div/div[3]/div[1]/div/a')

for element in abstract:
    print(x, element.text)
for element in doi_element:
    print(x, element.text)

driver.quit()

我的结果是空的(我从页面的链接中找到了 XPath)。 这是我的 bs4 代码:

response = requests.get('https://academic.oup.com/eurheartj/article-abstract/42/Supplement_1/ehab724.1650/6394300', headers=headers)
if response.status_code != 200:
    print('Status code:', response.status_code)
    raise Exception('Failed to fetch web page ')

page = BeautifulSoup(response.text, 'html.parser')

for entry in page.find_all("seciton", attrs={"class": "abstract"}):
    print(entry.get_text())

而且我的结果也是空的。 有什么问题?

【问题讨论】:

  • 尝试在requests 上设置标题。 headers = {'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:94.0) Gecko/20100101 Firefox/94.0'} 另外,最好使用response.raise_for_status()。还有一件事。它的section 不是seciton
  • 你有一个抽象的元素,doi_element,可以通过显示它来使用它 .get_attribute('innerHMTL') 等等。
  • 谢谢,也许问题出在标题上。但是我怎么知道请求函数使用的正确标头是什么?

标签: python selenium beautifulsoup


【解决方案1】:

我建议使用 beautifulsoup 而不是 selenium

正如 AlexDotis 在 cmets 中提到的,在您的 GET 请求中使用 headers 以获得成功的响应,即 200 Response。没有它你会得到一个404 Response

此代码将打印摘要我不确定 DOI 是什么意思,所以我把它留给你

import requests
from bs4 import BeautifulSoup

url = 'https://academic.oup.com/eurheartj/article/42/Supplement_1/ehab724.1650/6394300'
headers = {"User-agent":"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.120 Safari/537.36"}
r = requests.get(url, headers=headers)
soup = BeautifulSoup(r.text, 'lxml')

s = soup.find('section', class_='abstract')

divs = s.find_all('div', class_='sec')
for div in d:
    title = div.find('div', class_='title').text.strip()
    tex = None
    p_tex = div.find('p')
    if p_tex:
        tex = p_tex.text.strip()
    print(f'\n{title}\n{tex}\n')

【讨论】:

    猜你喜欢
    • 2012-07-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-01
    • 2013-04-29
    • 1970-01-01
    相关资源
    最近更新 更多